親オブジェクトが保存される前に、関連する祖父母にアクセスしたい状況があります。いくつかのハックを思いつくことができますが、これを達成するためのクリーンな方法を探しています。私の問題の実例として、次のコードを取り上げます。
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 である理由も理解しています。ただし、save を呼び出す前に、Rails が将来の関連付けへの直接参照を保持して、保存されていない部門オブジェクトを介して最後の行を委任できるようにしてほしいと思います。クリーンな回避策はありますか?
更新: 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 のテスト プロジェクトです。