对范围内的查询使用 OR [英] Using OR with queries in a scope

查看:28
本文介绍了对范围内的查询使用 OR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails3 中,我有:

In Rails3 I have:

Class Teacher
  #  active                 :boolean
  has_and_belongs_to_many :subjects

Class Subject
  #  active                 :boolean
  has_and_belongs_to_many :teachers

我正在尝试构建一个教师范围,该范围返回所有 active 或与 Subject 相关联的 Teachers,即 活动.

I am trying to construct a Teacher scope that returns all Teachers that are active or are associated with a Subject that is active.

这些作用域单独工作,但如何将它们作为单个作用域与 OR 组合在一起?

These scopes work individually, but how to combine them as a single scope with an OR?

scope :active_teachers, where(active: true)
scope :more_active_teachers, joins(:subjects).where(:subjects => {active: true})

我试过没有成功:

scope :active_teachers, where(active: true).or(joins(:subjects)
      .where(:subjects => {active: true}))

更新:

我以为我有一个解决方案,但这不再是延迟加载,两次命中数据库,而且——最重要的是——返回一个数组而不是一个 AR 对象!

I thought I had a solution, but this no longer lazy loads, hits the database twice and — most importantly — returns an array rather than an AR object!

scope :active_teachers, where(active: true) |
                        joins(:subjects).where(:subjects => {active: true})

推荐答案

你有 Squeel 来拯救你.更多详情此处.

You have Squeel to your rescue. More details here.

使用它,您可以定义如下内容:

Using that, you could define something like:

class Teacher
  ...
  scope :active_teachers, joins{subjects}.where {(active == true) | (subjects.active == true)}
  ...
end

这篇关于对范围内的查询使用 OR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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