Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I access an ActiveRecord grandparent association through a parent association that has not yet been saved?
    primarykey
    data
    text
    <p>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:</p> <pre><code>class Company &lt; ActiveRecord::Base has_many :departments has_many :custom_fields has_many :employees, :through =&gt; :departments end class Department &lt; ActiveRecord::Base belongs_to :company has_many :employees end class Employee &lt; ActiveRecord::Base belongs_to :department delegate :company, :to =&gt; :department end company = Company.find(1) # =&gt; &lt;Company id: 1&gt; dept = company.departments.build # =&gt; &lt;Department id: nil, company_id: 1&gt; empl = dept.employees.build # =&gt; &lt;Employee id: nil, department_id: nil&gt; empl.company # =&gt; Employee#company delegated to department.company, but department is nil </code></pre> <p>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?</p> <p>UPDATE: I've tried this in Rails 4 as well, here is a console session:</p> <pre><code>2.0.0-p247 :001 &gt; company = Company.find(1) Company Load (1.5ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = ? LIMIT 1 [["id", 1]] =&gt; #&lt;Company id: 1, name: nil, created_at: "2013-10-24 03:36:11", updated_at: "2013-10-24 03:36:11"&gt; 2.0.0-p247 :002 &gt; dept = company.departments.build =&gt; #&lt;Department id: nil, name: nil, company_id: 1, created_at: nil, updated_at: nil&gt; 2.0.0-p247 :003 &gt; empl = dept.employees.build =&gt; #&lt;Employee id: nil, name: nil, department_id: nil, created_at: nil, updated_at: nil&gt; 2.0.0-p247 :004 &gt; empl.company RuntimeError: Employee#company delegated to department.company, but department is nil: #&lt;Employee id: nil, name: nil, department_id: nil, created_at: nil, updated_at: nil&gt; 2.0.0-p247 :005 &gt; empl.department =&gt; nil </code></pre> <p>UPDATE 2: Here is a <a href="https://github.com/dissolved/activerecord_deep_obj_linking" rel="nofollow">test project on github</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload