Create association between two instancied objects

允我心安 提交于 2019-12-05 03:43:36

You can do like this:

a = Album.create( name: "My Album" )

p = Product.create( name: "Shampoo X" )
# OR
p = Product.create( name: "Shampoo X", album_id: a.id )
# OR
p.album = a
# OR
p.album_id = a.id
# OR 
a.products << a
# finish with a save of the object:
p.save

You may have to set the attribute accessible to album_id on the Product model (not sure about that).

Check @bdares' comment also.

Add the association when you create the Product:

a = Album.create( :name => "My Album" )
p = Product.create( :name => "Shampoo X", :album => a )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!