Rails habtm joins

I have this connection between categories, products and 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 for a given brand with these relationships? I try this, but I get an error

 b = Brand.find(1) Category.joins(:products).where(:products => b.products) 
+6
source share
2 answers

You did the right thing with the connection, just add a more complex definition:

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

HABTM is rarely controversial, if ever, with a good design and IM just about the only thing that Rails was wrong.

Fill in the xref table to join the products and categories and use has_many: on either side of the relationship so you get

 class Brand < ActiveRecord::Base has_many :products has_many categories :through => products # This is now allowed in Rails 3.x and above end class Category < ActiveRecord::Base belongs_to :product_category has_many :products :through => product_category end class Product < ActiveRecord::Base belongs_to :brand belongs_to :product_category has_many :categories :through => product_category end class ProductCategory < ActiveRecord::Base has_many :products has_many :categories end 

This gives you maximum flexibility with a minimal amount of code re-factoring for you plus a more intuitive way to get any data that you need on either side of the relationship and allow you to achieve the following

 b = Brand.find(1) b.categories.all 

Update The above code is completely untested, and I just fixed the stupid thing I did. If you have any problems with this, go back

+4
source

All Articles