【问题标题】:scope for attribute in belong_to objectbelongs_to 对象中的属性范围
【发布时间】:2015-06-20 01:33:00
【问题描述】:

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

class CompanyBranch < ActiveRecord::Base
  belongs_to :company
  ...
end

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

scope :category, -> (category_id) { where company.category_id: category_id }

但这不起作用。这样做的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 scope scoping


    【解决方案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) }
    

    【讨论】:

      【解决方案2】:
      class CompanyBranch < ActiveRecord::Base
          belongs_to :company
          scope :by_category, -> (cat) { joins(:companies).where(companies: {category: cat}) }
          # ...
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-03
        • 1970-01-01
        • 2016-07-01
        • 2012-02-22
        • 1970-01-01
        • 1970-01-01
        • 2017-12-16
        • 2016-09-20
        相关资源
        最近更新 更多