在两个instancied对象之间创建关联

时间:2012-12-26 00:01:15

标签: ruby-on-rails associations has-many belongs-to

我有两种型号:(专辑和产品)

1)内部模型

Inside album.rb:

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

inside product.rb:

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

2)使用“ rails console ”,如何设置关联(所以我可以使用“&lt;%= Product.first.album.name%&gt;”)?

e.g。

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?

2 个答案:

答案 0 :(得分:11)

你可以这样做:

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的评论。

答案 1 :(得分:2)

创建产品时添加关联:

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