这是 Ruby 1.9.3p194 和 Rails 3.2.8
应用程序/模型/所有者.rb:
class Owner < ActiveRecord::Base
attr_accessible :name
has_many :pets
end
应用程序/模型/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
好吧,现在看看会发生什么……
# 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"]
我的问题:我怎样才能让 rails 初始化 shaggy.pets 的元素以使其所有者设置为 shaggy (确切的对象),不仅是在首次构建/创建宠物对象时,而且即使它们是从自动加载的通过关联的数据库?
加分项:让它在 Rails 2.3.5 中也能正常工作。