我在类别,产品和品牌之间具有这种关系:
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)
最佳答案
您对联接做了正确的事情,只是在其中定义中添加了更复杂的内容:
Category.joins(:products).where(:products => {:brand_id => 1})
关于ruby-on-rails - Rails Habtm加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14243566/