本文介绍了如何通过尚未保存的父关联访问ActiveRecord祖父母关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在保存父对象之前,我想访问关联的祖父母。我可以想到一些骇客,但我正在寻找一种干净的方法来实现这一目标。以下面的代码来说明我的问题:

I have a situation where I would like access to an associated grandparent before the parent object is saved. I can think of several hacks, but I'm searching for a clean way to accomplish this. Take the following code as an illustration of my problem:

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之前直接引用预期的关联,以便最后一行可以通过未保存的Department对象委派。

I'm using Rails 3.2.15. I understand what is happening here, and I understand why empl.department_id is nil; though I wish Rails held a direct reference to the prospective association prior to calling save, such that the last line could be delegated through the unsaved department object. Is there a clean work around?

更新:我也在Rails 4中尝试过,这是一个控制台会话:

UPDATE: I've tried this in Rails 4 as well, here is a console session:

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:这是。

推荐答案

请查看<$ c 和。在不同情况下构建和获取关联记录时,此选项将处理双向分配。

Please look into the :inverse_of option for belongs_to and has_many. This option will handle two-way assignments when building and fetching associated records in different cases.

来自,用于 ActiveRecord :: Associations :: ClassMethods 在文档中:

这篇关于如何通过尚未保存的父关联访问ActiveRecord祖父母关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 02:25