【问题标题】:How to write scope with belongs_to object?如何用 belongs_to 对象编写范围?
【发布时间】:2012-12-03 07:48:16
【问题描述】:

我有以下型号

模型

Job
  belongs_to :company
Company
  has_many :jobs

现在我使用以下方法选择所有接受CompanyJobs

def self.with_accepted_company
  Job.all.reject {|job| job.company.state != "accepted" }
end

但我想为此使用作用域并将其与其他作用域一起使用。这是否可以在Job 模型中编写该范围?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rails-activerecord scopes


    【解决方案1】:

    我会做这样的事情(来自http://guides.rubyonrails.org/active_record_querying.html

    class Job
      scope :accepted_with_active_company, ->() {
        joins(:company).where('companies.state' => "accepted") 
      }
    end
    

    【讨论】:

    • 我在使用这个范围时遇到错误>> Job.accepted_with_active_company.inspect ActiveRecord::ConfigurationError: Association named 'companies' was not found; perhaps you misspelled it? from /Users/rege/.rvm/gems/ruby-1.9.3-p194@ckdatabase/gems/activerecord-3.2.8/lib/active_record/associations/join_dependency.rb:112:in `build'
    • 错误信息告诉你没有名为:companies 的关联。原始代码假定它是has_many 关系,但实际上它是belongs_to,你应该做的是使用joins(:company) 而不是joins(:companies)。我已经编辑了答案以反映这一点
    【解决方案2】:

    这里是 where 子句的另一种语法:

    class Job
      scope :accepted_with_active_company, ->() {
        joins(:company).where(companies: { state: 'accepted' }) 
      }
    end
    

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 1970-01-01
      • 2016-07-01
      • 2012-11-13
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多