Rails ActiveRecord where 子句中的或 & and

问题描述 投票:0回答:4

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

a = true 且 b = true 且 ( 0< c <1 or d=1), a, b, c, d are columns.

我可以要一些类似的东西吗:

 Route.where(:a => true,
             :b => true,
             :c => 0..1 OR :d=1
             ).all          
ruby-on-rails ruby-on-rails-3 activerecord
4个回答
19
投票

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

假设您使用的是 SQLite 或 Postgres:

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

我还没有测试过这段代码,但我怀疑它可能适合你。请注意,这是不太“可移植”的代码;如果您更改正在使用的数据库,查询可能会中断。


16
投票

在 Rails 4 中你也可以这样做

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

这将找到 c 是 1 或 2 的位置。


4
投票

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

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

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

AND 运算符的行为类似。


0
投票

ActiveRecords 中缺少常用方法:

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

您可以使用以下补丁添加它:

module ActiveRecordSearch

  def where_one_of fields
    relation = nil
    fields.each do |key, value|
      next unless value.present?

      where = self.where(key => value)
      relation = relation ? relation.or(where) : where
    end
    relation
  end

end

ActiveRecord::Relation.class_eval do
  include ActiveRecordSearch
end

ActiveRecord::Base.class_eval do
  extend ActiveRecordSearch
end
© www.soinside.com 2019 - 2024. All rights reserved.