怎样用belongs_to对象写作用域? [英] How to write scope with belongs_to object?

查看:95
本文介绍了怎样用belongs_to对象写作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号

模型

Job
  belongs_to :company
Company
  has_many :jobs

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

Right now I select all the Jobs which have an accepted Company using the following method:

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

但是我想为此使用范围,并将其与其他范围一起使用.可以在Job模型中写入该范围吗?

But I would like to use scope for that and use it with other scopes. Is this possible to write that scope in the Job model?

推荐答案

我会做类似的事情(来自 http://guides.rubyonrails.org/active_record_querying.html )

I would do something like this (from http://guides.rubyonrails.org/active_record_querying.html)

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

这篇关于怎样用belongs_to对象写作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆