我在类别,产品和&品牌:
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
如何通过此关系选择指定品牌的所有类别? 我试试这个,但得到一个错误
b = Brand.find(1)
Category.joins(:products).where(:products => b.products)
答案 0 :(得分:8)
你使用连接做了正确的事情,只需添加一个更复杂的定义:
Category.joins(:products).where(:products => {:brand_id => 1})
答案 1 :(得分:4)
有争议的HABTM很少,如果有的话,很好的设计和IMO只是Rails唯一出错的地方。
引入外部参照表来加入产品和类别,并在关系的两边使用has_many:through,以便最终得到
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
这为您提供了最佳的灵活性,为您提供了最少量的代码重新分解,以及更直观的路径,可以在关系的任何一方获得您需要的任何数据,并使您能够实现以下目标
b = Brand.find(1)
b.categories.all
<强>更新强> 以上是完全未经测试的代码,我刚刚纠正了我犯的一个明显愚蠢的错误。如果你有任何问题,那么回来