【发布时间】:2012-08-30 03:47:49
【问题描述】:
这是在 Ruby 1.9.3p194 和 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
好吧,现在看看会发生什么……
# 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 中也能正常工作。
【问题讨论】:
-
你不能,ActiveRecord 不适合这个。你可能想看看 DataMapper。
标签: ruby-on-rails ruby activerecord associations arel