2016-03-28 45 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