我有一种情况,我想在保存父对象之前访问关联的祖父母。我可以想到几个黑客,但我正在寻找一种干净的方法来完成这个。以以下代码为例说明我的问题:
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:这是github 上的一个测试项目。