ruby-on-rails – 在两个instancied对象之间创建关联

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在两个instancied对象之间创建关联前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个型号:(专辑和产品)

1)内部模型

在album.rb里面:

  1. class Album < ActiveRecord::Base
  2. attr_accessible :name
  3. has_many :products
  4. end

内部product.rb:

  1. class Product < ActiveRecord::Base
  2. attr_accessible :img,:name,:price,:quantity
  3. belongs_to :album
  4. end

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

例如

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

解决方法

你可以这样做:
  1. a = Album.create( name: "My Album" )
  2.  
  3. p = Product.create( name: "Shampoo X" )
  4. # OR
  5. p = Product.create( name: "Shampoo X",album_id: a.id )
  6. # OR
  7. p.album = a
  8. # OR
  9. p.album_id = a.id
  10. # OR
  11. a.products << a
  12. # finish with a save of the object:
  13. p.save

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

检查@bdares的评论.

猜你在找的Ruby相关文章