9

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

1) 内部模型

里面的专辑.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 ”,我如何设置关联(所以我可以使用“<%= 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?
4

2 回答 2

12

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.

于 2012-12-26T00:04:37.400 回答
2

创建产品时添加关联:

a = Album.create( :name => "My Album" )
p = Product.create( :name => "Shampoo X", :album => a )
于 2012-12-26T00:28:16.173 回答