我是Ruby和Rails的新手,继承了一个代码库我的目标是更好地理解ror,而不仅仅是修复这个特定的bug。
[就像一个与我试图理解的事物类型无关的例子,代码有时调用@employee.build_current_employmentGrepping显示build_current_employment没有在代码库中的任何地方声明,但是函数名表明它应该是我们编写的代码,而不是来自第三方库的代码(这也使得Google没有帮助)最后,我发现activerecord是在运行时创建函数定义的,基于我们自己的类名,这是一种秘密的握手垃圾,我希望这就是问题所在。]
在我们的代码中,app/models包含employee.rb(声明类employee)和time-off-type.rb(声明类timeofftype),而app/models/employee包含time-off-type.rb(声明类employee::timeofftype)。每一个都继承自activerecord::base而不是其他任何东西。
类Employee包含

has_many :time_off_types, class_name: '::Employee::TimeOffType'

app/models/employee中的类timeofftype包含
belongs_to :employee
belongs_to :company_time_off_type, class_name: '::TimeOffType', foreign_key: 'time_off_type_id'

而另一个TimeOffType并没有直接连接到它们中的任何一个,但是它确实有
belongs_to :company

我已经为员工添加了以下函数
def assign_time_off_types

  # junk = TimeOffType.new      # Uncommenting this fixes the problem
  # puts junk.class.name        # Outputs Employee::TimeOffType
  # junk = Employee::TimeOffType.new        # Uncommenting this also fixes the problem
  # junk = ::TimeOffType.new    # Uncommenting this doesn't fix the problem
  # junk = nil

  company.time_off_types.each do |i|
    new_time_off_entry = Employee::TimeOffType.create(employee_id: self.id, time_off_type_id: i.id)
#   new_time_off_entry = ::Employee::TimeOffType.create(employee_id: self.id, time_off_type_id: i.id)   # Produces the same error
#   new_time_off_entry = TimeOffType.create(employee_id: self.id, time_off_type_id: i.id)               # Produces the same error
  end
end

调用此函数会产生错误unknown attribute 'employee_id' for TimeOffType.但是,如果我取消注释前两个“垃圾”行中的一个,则一切正常,数据库条目将按预期创建,等等。创建后是否立即清除垃圾也无所谓。
尽管我明确要求输入time off type,但为什么新的TimeOffType条目的类型是TimeOffType而不是Employee::TimeOffType?
创建TimeOffType对象如何解决此问题?为什么它默认为Employee::TimeOffType?
编辑:按要求
class Employee < ActiveRecord::Base

class Employee::TimeOffType < ActiveRecord::Base

class TimeOffType < ActiveRecord::Base

class Company < ActiveRecord::Base

最佳答案

您很可能遇到了Constant Autoloading问题,因为在不同的作用域中有两个同名的不同类。
通常require_dependency会解决这个问题。

关于ruby-on-rails - Rails/ActiveRecord-如何创建不使用的对象会更改另一个对象的类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39397991/

10-09 00:45
查看更多