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
source share