Rails创建对象has_many

时间:2016-03-28 18:13:48

标签: ruby-on-rails

我的模特

class Collection < ActiveRecord::Base
  has_many :outfits
  has_many :products, through: :outfits
end

class Outfit < ActiveRecord::Base 
  belongs_to :product
  belongs_to :collection
end

class Product < ActiveRecord::Base
  has_many :outfits
  has_many :collections, through: :outfits
end

我想在收藏模型中保存产品

所以一个集合中的产品很少

我该怎么办?我有点挣扎

它尝试了类似的东西

p = Product.find_by_code('0339').id

p.collections.create(product_id:p1)

但我想我错了

1 个答案:

答案 0 :(得分:1)

当您通过through集合进行链接时,您不需要引用父亲的ID,因为这是已知的。

而不是:

p = Product.find_by_code('0339').id # NOTE that you have an 'id' not an object here
p.collections.create(product_id:p1) # you can't call an association on the id

建立两个现有模型之间的关联(我假设你的模型中有其他字段;我以name为例)。

p = Product.find_by(code: '0339')
c = Collection.find_by(name: 'Spring 2016 Clothing')
o = Outfit.new(name: 'Spring 2016 Outfit', product: p, collection: c)
o.save! 

假设存在pc并假设o通过验证,那么您现在在一个产品和一个集合之间使用新服装作为连接表进行关联。

p.reload
p.collections.count # => 1

c.reload
c.products.count # => 1