Search code examples
ruby-on-railsjoinhas-and-belongs-to-many

Rails habtm joins


I have this relationship between categories, products & brands:

class Brand < ActiveRecord::Base
  has_many :products
end

class Category < ActiveRecord::Base
  has_and_belongs_to_many :products
end

class Product < ActiveRecord::Base
  has_and_belongs_to_many :categories
  belongs_to :brand
end

How can I select all categories by specified brand with this relations? I try this but get an error

b = Brand.find(1)
Category.joins(:products).where(:products => b.products)

Solution

  • You did the right thing with the join, just add a more complex where definition:

    Category.joins(:products).where(:products => {:brand_id => 1})