ruby on rails - How to query for the products belonging to category and sub categories the correct way -
categories , sub categories independent models. , each category have sub categories.
while creating product, admin has select category , sub category.
following models have come with
class product < activerecord::base belongs_to :category end class category < activerecord::base has_many :products end class sub < activerecord::base has_many :products end
here schema products
create_table "products", force: :cascade |t| t.string "name" t.integer "price" t.integer "category_id" t.integer "sub_id" end
the product created this
product.create(name: "messi magnet custom",category_id: 1, sub_id: 2)
and querying products belong particular category , sub category this
product.where("category_id = ? , sub_id = ?",9,3)
is there thing wrong associations having? , improve this?
class category < activerecord::base has_many :products has_many :sub_categories end class subcategory < activerecord::base has_many :products belongs_to :category #sub_categories table have reference category, i.e., category_id column end class product < activerecord::base belongs_to :category belongs_to :sub #you need add end
Comments
Post a Comment