我有一个属于公司的模型CompanyBranch:
class CompanyBranch < ActiveRecord::Base
belongs_to :company
...
end
公司有一个属性“category_id”。现在我想通过公司的category_id来确定CompanyBranch的范围。像这样:
scope :category, -> (category_id) { where company.category_id: category_id }
但那不起作用。什么是正确的方法呢?
答案 0 :(得分:2)
class CompanyBranch < ActiveRecord::Base
belongs_to :company
scope :by_category, -> (cat) { joins(:companies).where(companies: {category: cat}) }
# ...
end
答案 1 :(得分:1)
您还必须将其加入类别表,如下所示:
scope :category, lambda { | category_id | joins("INNER JOIN categories on company_branches.category_id = categories.id").where("company.category_id: category_id)", category_id) }