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

ros*_*ose 8 ruby-on-rails associations has-many belongs-to

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

1)内部模型

在album.rb里面:

class Album < ActiveRecord::Base
  attr_accessible :name
  has_many :products
end
Run Code Online (Sandbox Code Playgroud)

内部product.rb:

class Product < ActiveRecord::Base
  attr_accessible :img, :name, :price, :quantity
  belongs_to :album
end
Run Code Online (Sandbox Code Playgroud)

2)使用" rails console ",如何设置关联(所以我可以使用"<%= 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?
Run Code Online (Sandbox Code Playgroud)

MrY*_*iji 10

你可以这样做:

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
Run Code Online (Sandbox Code Playgroud)

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

检查@bdares的评论.