这可以通过示例来最好地解释。以下是简单的事:用has_many关联预先填充创建Rails模型的实例
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>]
不过,我想所有的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>]
这可能吗?理想情况下,'default'对象仍将以与我明确运行第2a行相同的方式关联,以便在保存父Foo对象时保存它。