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

查看:81
本文介绍了对范围中的查询使用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

我正在尝试构造一个教师范围,该范围返回所有活动或与主题是有效的

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})

我已经尝试过但没有成功:

I've tried this without success:

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

UPDAT E:

我以为我有一个解决方案,但这不再是延迟加载,它两次访问数据库,最重要的是,返回一个数组而不是一个

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天全站免登陆