创建两个instancied对象之间的关联(Create association between t

2019-08-04 17:02发布

我有两个型号:(相册和产品)

1)内部模型

内部album.rb:

class Album < ActiveRecord::Base
  attr_accessible :name
  has_many :products
end

内部product.rb:

class Product < ActiveRecord::Base
  attr_accessible :img, :name, :price, :quantity
  belongs_to :album
end

2)使用“ 轨道控制台 ”,哪能设定关联(所以可以用“<%= Product.first.album.name%>”)?

a = Album.create( :name => "My Album" )
p = Product.create( :name => "Shampoo X" )
# what's next? how can i set the album and the product together?

Answer 1:

你可以这样做:

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

您可能需要设置访问album_id的产品型号(不知道这一点)的属性。

检查@bdares'评论也。



Answer 2:

当您创建的添加产品的关联:

a = Album.create( :name => "My Album" )
p = Product.create( :name => "Shampoo X", :album => a )


文章来源: Create association between two instancied objects