2016-03-28 44 views
1

我的模型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 

我想保存在产品集合模型对象的has_many

这样一个集合可以有几个产品在它

我该怎么办呢?我和你在一起有点挣扎

它已经试过这样的事情

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

p.collections.create(product_id:p1) 

,但我想我错了

+0

你能写出你想建模的关系吗?这会使它更容易理解。例如,收藏品有很多服装,服装有很多产品,但产品只有一种服装? –

+0

@MatthewCliatt我的主要目标是在许多'集合'中有一个'产品' – user

+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通过验证,那么你现在可以使用新装备的连接表一个产品和一个集之间的assocaition。

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

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

omg thx man @GSP。但为什么我需要重新加载? – user

+1

'reload'可能没有必要;在这个测试中,我只是确保构建'Outfit'实例将立即反映在新的查询中 – GSP