Rails Habtm加入 [英] Rails habtm joins
本文介绍了Rails Habtm加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在类别,产品和产品之间具有这种关系品牌:
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)
推荐答案
您对联接做了正确的事情,只是在定义中添加了更复杂的地方:
You did the right thing with the join, just add a more complex where definition:
Category.joins(:products).where(:products => {:brand_id => 1})
这篇关于Rails Habtm加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文