This is in Ruby 1.9.3p194, with Rails 3.2.8
app/models/owner.rb:
class Owner < ActiveRecord::Base
attr_accessible :name
has_many :pets
end
app/models/pet.rb:
class Pet < ActiveRecord::Base
attr_accessible :name, :owner
belongs_to :owner
end
db/migrate/20120829184126_create_owners_and_pets.rb:
class CreateOwners < 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
Alright, now watch what happens...
# rake db:migrate
# rails console
irb> shaggy = Owner.create(:name => 'Shaggy')
irb> shaggy.pets.build(:name => 'Scooby Doo')
irb> shaggy.pets.build(:name => 'Scrappy Doo')
irb> shaggy.object_id
=> 70262210740820
irb> shaggy.pets.map{|p| p.owner.object_id}
=> [70262210740820, 70262210740820]
irb> shaggy.name = 'Shaggie'
irb> shaggy.name
=> "Shaggie"
irb> shaggy.pets.map{|p| p.owner.name}
=> ["Shaggie", "Shaggie"]
irb> shaggy.save
irb> shaggy.reload
irb> shaggy.object_id
=> 70262210740820
irb> shaggy.pets.map{|p| p.owner.object_id}
=> [70262211070840, 70262211079640]
irb> shaggy.name = "Fred"
irb> shaggy.name
=> "Fred"
irb> shaggy.pets.map{|p| p.ower.name}
=> ["Shaggie", "Shaggie"]
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?
Bonus points: Make it work in Rails 2.3.5 as well.