【问题标题】:Or & and in Rails ActiveRecord where clauseOr & and 在 Rails ActiveRecord where 子句中
【发布时间】:2012-06-09 06:08:25
【问题描述】:

我正在使用 Rails 3.2,并且我有一个数据库表,我想在其中查找符合以下条件的所有行:

a = true and b = true and (0

我可以有类似的东西吗:

 Route.where(:a => true,
             :b => true,
             :c => 0..1 OR :d=1
             ).all          

【问题讨论】:

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


【解决方案1】:

我可能是错的,但我认为您不能使用基于 Arel 的 where 函数形成该查询;您需要自己形成数据库查询字符串。

假设您使用的是 SQLite 或 Postgres:

Route.where("a = true and b = true and ((c > 0 and c < 1) or d = 1)").all

我没有测试过这段代码,但我怀疑它可能会为你完成这项工作。请注意,这是不太“便携”的代码;如果您更改正在使用的数据库,查询可能会中断。

【讨论】:

  • where('a = :true and b = :true and ((c &gt; :lo and c &lt; :hi) or d = :d', :true =&gt; true, :lo =&gt; 0, :hi =&gt; 1, :d =&gt; 1) 会更安全,不同的数据库对“true”使用不同的东西。甚至.where(:a =&gt; true, :b =&gt; true).where('c &gt; :lo and c &lt; :hi) or d = :d', ...).
【解决方案2】:

在 Rails 4 中你也可以这样做

Route.where(:a =&gt; true,:b =&gt; true,:c =&gt; [1,2]).all

这将找出 c 是 1 还是 2。

【讨论】:

  • .all 是必需的吗?我认为这是默认的。
  • 是的 .all 不是必需的,我只是让它与问题保持一致。
  • 这很好用。谢谢。你也可以使用这样的符号:Route.where(a: true, b: true, c: [1,2])
【解决方案3】:

我认为 Rob 关于 arel 不支持 OR 的说法是正确的。来自arel site

尚不支持 OR 运算符。它将像这样工作:

users.where(users[:name].eq('bob').or(users[:age].lt(25)))

AND 运算符的行为类似。

【讨论】:

  • 我是新手。学习如何使用网站。直接点了上去。还不知道如何“接受”。
  • 对不起,我把你和原来的问题作者弄混了。
猜你喜欢
  • 1970-01-01
  • 2021-02-02
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-14
  • 2012-08-16
  • 2015-09-11
相关资源
最近更新 更多