How to get list of categories for a store
I have a Store Model that can have multiple products. Each product has a category.
What is the most optimal way to g开发者_JAVA百科et the list of categories for products in a store?
For eg. Store A has Products A (Cat1), Product B(Cat1), Product C (Cat2)
I want Cat1, Cat2 when I pass the Store A's id.
@store = Store.find(ID)
@categories = @store.products.map {|p| p.category }
So,
- Store has_many products (each product belongs_to Store): one-to-many relation
- Each product has_one category (each category belongs_to a product): one-to-one relation
In your Product table, you should have store_id field, and in your Category table you should have a product_id field. Then set the has_many and belong_to relation in your Models.
# 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
精彩评论