[英]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)
你用连接做了正确的事情,只需添加一个更复杂的定义:
Category.joins(:products).where(:products => {:brand_id => 1})
Controversially HABTM's are rarely, if ever, a good design and IMO just about the only thing Rails got wrong. 有争议的HABTM很少,如果有的话,很好的设计和IMO只是Rails唯一出错的地方。
Introduce an xref table to join products and categories and use has_many :through on both sides of the relationship so you end up with 引入一个外部参照表来加入产品和类别,并在关系的两边使用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
This gives you the best flexibility with the least amount of code re-factoring for you plus a much more intuitive path to get whatever data you need on either side of the relationship and will enable you to achieve the following 这为您提供了最佳的灵活性,为您提供了最少量的代码重新分解,以及更直观的路径,可以在关系的任何一方获得您需要的任何数据,并使您能够实现以下目标
b = Brand.find(1)
b.categories.all
Update The above is totally untested code and I have just corrected a glaringly stupid mistake I made. 更新以上是完全未经测试的代码,我刚刚纠正了我犯的一个明显愚蠢的错误。 If you have any issues implementing this then come back 如果您在实施此问题时遇到任何问题,请返回
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.