在两个实例化对象之间创建关联

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

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)使用“ rails console ”,如何设置关联(所以我可以使用“”)?

例如

 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? 

你可以这样做:

 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 

您可能必须在Product模型上设置album_id可访问的属性(不确定)。

检查@bdares的评论。

在创建产品时添加关联:

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