Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I get an ActiveRecord::Association to initialize a parent's auto-loaded children's parent references to point at the actual parent object?
    text
    copied!<p>This is in Ruby 1.9.3p194, with Rails 3.2.8</p> <p>app/models/owner.rb:</p> <pre><code>class Owner &lt; ActiveRecord::Base attr_accessible :name has_many :pets end </code></pre> <p>app/models/pet.rb:</p> <pre><code>class Pet &lt; ActiveRecord::Base attr_accessible :name, :owner belongs_to :owner end </code></pre> <p>db/migrate/20120829184126_create_owners_and_pets.rb:</p> <pre><code>class CreateOwners &lt; ActiveRecord::Migration def change create_table :owners do |t| t.string :name t.timestamps end create_table :pets do |t| t.string :name t.integer :owner_id t.timestamps end end end </code></pre> <p>Alright, now watch what happens...</p> <pre><code># rake db:migrate # rails console irb&gt; shaggy = Owner.create(:name =&gt; 'Shaggy') irb&gt; shaggy.pets.build(:name =&gt; 'Scooby Doo') irb&gt; shaggy.pets.build(:name =&gt; 'Scrappy Doo') irb&gt; shaggy.object_id =&gt; 70262210740820 irb&gt; shaggy.pets.map{|p| p.owner.object_id} =&gt; [70262210740820, 70262210740820] irb&gt; shaggy.name = 'Shaggie' irb&gt; shaggy.name =&gt; "Shaggie" irb&gt; shaggy.pets.map{|p| p.owner.name} =&gt; ["Shaggie", "Shaggie"] irb&gt; shaggy.save irb&gt; shaggy.reload irb&gt; shaggy.object_id =&gt; 70262210740820 irb&gt; shaggy.pets.map{|p| p.owner.object_id} =&gt; [70262211070840, 70262211079640] irb&gt; shaggy.name = "Fred" irb&gt; shaggy.name =&gt; "Fred" irb&gt; shaggy.pets.map{|p| p.ower.name} =&gt; ["Shaggie", "Shaggie"] </code></pre> <p>My question: How can I get rails to initialize the elements of shaggy.pets to have their owners set to shaggy (the exact object), not only when the pet objects are first built/created, but even when they are auto-loaded from the database via the association?</p> <p>Bonus points: Make it work in Rails 2.3.5 as well.</p>
 

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