これは例によって最もよく説明されます。以下は簡単です。
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>]
ただし、2行目を明示的に実行せずにすべてのFooオブジェクトをBarで初期化する必要があります。
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オブジェクトが保存されるときに保存されます。