2014-10-29 83 views
0

我知道麥吧必須是錯誤的方式,我建立我的分貝,但請花一分鐘回答:我正在建立一個超市模型,其中1個用戶有一個購物清單,每個列表有很多產品。 所以我要做的就是:鋼筋協會belongs_to

class User < ActiveRecord::Base 
    has_many :lists 
end 

class List < ActiveRecord::Base 
    belongs_to :user 
    has_many :products 
end 

class Product < ActiveRecord::Base 
    ???? 
end 

名單有幾個產品,但產品不屬於名單。我應該怎麼做才能讓用戶擁有多個列表,並列出許多產品? 問候,

回答

0

有一個類,通過has_many通過鏈接它們。

class ListItem < ActiveRecord::Base 
    belongs_to :list 
    belongs_to :product 
end 

class List < ActiveRecord::Base 
    belongs_to :user 
    has_many :list_items 
    has_many :products, through: :list_items 
end 
+0

我可以我相信我需要一個額外的班級來做到這一點。我認爲這種關聯是有用的,並且總是發生。您是否需要管理有物品購物清單的用戶列表,這是您繼續的方式嗎? – Yann 2014-10-29 15:30:11

+0

您可以使用has_and_belongs_to_many來代替,它有db表,但沒有模型。 – 2014-10-29 15:45:12

0

您不需要額外的班級。 Rails可以用has_and_belongs_to_many_association

你的情況,管理這個對你來說,這將是:

class User < ActiveRecord::Base 
    has_many :lists 
end 

class List < ActiveRecord::Base 
    belongs_to :user 
    has_and_belongs_to_many :products 
end 

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :lists 
end 

當然,你需要添加在遷移的連接表:

create_table :lists_products, id: false do |t| 
    t.belongs_to :list 
    t.belongs_to :product 
end