这最好通过例子来解释。以下操作很简单:
class Foo < ActiveRecord::Base
has_many :bars
end
1a>> foo = Foo.new
=> #<Foo id: nil>
2a>> foo.bars << Bar.new
=> [#<Bar id: nil, foo_id: nil>]
3a>> foo.bars
=> [#<Bar id: nil, foo_id: nil>]
但是,我希望使用 Bar 初始化所有 Foo 对象,而不必显式运行第 2 行:
class Foo < ActiveRecord::Base
has_many :bars
# [...] Some code here
end
1b>> foo = Foo.new
=> #<Foo id: nil>
2b>> foo.bars
=> [#<Bar id: nil, foo_id: nil>]
这可能吗?理想情况下,“默认”对象仍将以与我明确运行第 2a 行相同的方式关联,以便在保存父 Foo 对象时保存它。