TAGS :Viewed: 3 - Published at: a few seconds ago

[ How to query for the products belonging to category and sub categories the correct way ]

Categories and Sub categories are independent models. And each category will have all the sub categories.

While creating a product, the admin has to select a category and the sub category.

Following are the models I have come up 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 is the schema for the products

create_table "products", force: :cascade do |t|
    t.string   "name"
    t.integer  "price"
    t.integer  "category_id"
    t.integer  "sub_id"
  end

The product is created with something like this

Product.create(name: "Messi magnet custom",category_id: 1, sub_id: 2)

And I am querying all the products that belong to a particular category and sub category like this

Product.where("category_id = ? AND sub_id = ?",9,3)

Is there any thing wrong with the associations I am having? And anything I could do improve this?

Answer 1


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 now have a reference to category, i.e., category_id column
end

class Product < ActiveRecord::Base
  belongs_to :category
  belongs_to :sub #You need to add this too
end