2011-05-17 46 views
0

我有一個商店模型可以有多個產品。每個產品都有一個類別。如何獲得商店類別的列表

什麼是獲得商店中產品類別列表的最佳方式?

例如,商店A有產品A(Cat1),產品B(Cat1),產品C(Cat2)

當我通過商店A的ID時,我想要Cat1,Cat2。

回答

0
@store = Store.find(ID) 
@categories = @store.products.map {|p| p.category } 
0

所以,

  1. 商店的has_many產品(每個產品belongs_to的商店):一個一對多的關係
  2. 每個產品HAS_ONE類別(每個類別belongs_to的產品):一到一個關係

在產品表中,你應該有STORE_ID場,並在分類表,你應該有一個PRODUCT_ID場。然後在您的模型中設置has_manybelong_to關係。

# beware of the use of pluralization 

# Store model 
class Store < ActiveRecord::Base 
    has_many :products      
end 

# Product model 
class Product < ActiveRecord::Base 
    belongs_to :store 
    has_one :category 
end 

# Category model 
class Category < ActiveRecord::Base 
    belongs_to :product 
end 

# e.g. access category of a product in your Store Controller 
# or loop it in your Store view 
@store = Store.find_by_id(myInt) 
@firstProductCategory = @store.products[0].category.name 
+0

我不認爲他想要一個產品的has_many類別,類別屬於一個獨特的產品。 – grzuy 2011-05-17 03:53:27