Belong_to 对象中属性的范围

nto*_*ier 5 scope ruby-on-rails scoping ruby-on-rails-4

我有一个属于公司的模型 CompanyBranch:

class CompanyBranch < ActiveRecord::Base
  belongs_to :company
  ...
end
Run Code Online (Sandbox Code Playgroud)

公司有一个属性“category_id”。现在我想通过公司的category_id 来确定CompanyBranch 的范围。像这样的东西:

scope :category, -> (category_id) { where company.category_id: category_id }
Run Code Online (Sandbox Code Playgroud)

但这是行不通的。这样做的正确方法是什么?

Sau*_*abh 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) }
Run Code Online (Sandbox Code Playgroud)