【发布时间】:2013-10-23 21:53:38
【问题描述】:
我有一种情况,我想在保存父对象之前访问关联的祖父母。我可以想到几个黑客,但我正在寻找一种干净的方法来完成这个。以以下代码为例说明我的问题:
class Company < ActiveRecord::Base
has_many :departments
has_many :custom_fields
has_many :employees, :through => :departments
end
class Department < ActiveRecord::Base
belongs_to :company
has_many :employees
end
class Employee < ActiveRecord::Base
belongs_to :department
delegate :company, :to => :department
end
company = Company.find(1) # => <Company id: 1>
dept = company.departments.build # => <Department id: nil, company_id: 1>
empl = dept.employees.build # => <Employee id: nil, department_id: nil>
empl.company # => Employee#company delegated to department.company, but department is nil
我使用的是 Rails 3.2.15。我明白这里发生了什么,也明白为什么 empl.department_id 为 nil;虽然我希望 Rails 在调用 save 之前直接引用预期关联,这样最后一行可以通过未保存的部门对象委托。有干净的工作吗?
更新:我也在 Rails 4 中尝试过,这是一个控制台会话:
2.0.0-p247 :001 > company = Company.find(1)
Company Load (1.5ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = ? LIMIT 1 [["id", 1]]
=> #<Company id: 1, name: nil, created_at: "2013-10-24 03:36:11", updated_at: "2013-10-24 03:36:11">
2.0.0-p247 :002 > dept = company.departments.build
=> #<Department id: nil, name: nil, company_id: 1, created_at: nil, updated_at: nil>
2.0.0-p247 :003 > empl = dept.employees.build
=> #<Employee id: nil, name: nil, department_id: nil, created_at: nil, updated_at: nil>
2.0.0-p247 :004 > empl.company
RuntimeError: Employee#company delegated to department.company, but department is nil: #<Employee id: nil, name: nil, department_id: nil, created_at: nil, updated_at: nil>
2.0.0-p247 :005 > empl.department
=> nil
更新 2:这是test project on github。
【问题讨论】:
-
多么奇怪。我必须稍后再试一次。昨晚工作得很愉快。检查
empl.association(:department) == Employee.new.association(:department)... -
该表达式的结果是
false。我看到关联上有一个实例变量@target,它似乎总是nil(即使是保存的记录)。我不知道@target应该是什么,但它包含我想要的参考对我来说是有意义的。
标签: ruby-on-rails ruby activerecord