ActiveRecord OR 查询

发布于 2024-09-18 08:55:52 字数 277 浏览 4 评论 0原文

如何在 Rails 3 ActiveRecord 中执行 OR 查询。我找到的所有示例都只有 AND 查询。

编辑:OR 方法自 Rails 5 起可用。请参阅 ActiveRecord::QueryMethods

How do you do an OR query in Rails 3 ActiveRecord. All the examples I find just have AND queries.

Edit: OR method is available since Rails 5. See ActiveRecord::QueryMethods

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

寄离 2024-09-25 08:55:52

如果要对一列的值使用 OR 运算符,可以将数组传递给 .where,ActiveRecord 将使用 IN(value,other_value)

Model.where(:column => ["value", "other_value"]

输出:

SELECT `table_name`.* FROM `table_name` WHERE `table_name`.`column` IN ('value', 'other_value')

这应该在单列上实现相当于 OR 的效果

If you want to use an OR operator on one column's value, you can pass an array to .where and ActiveRecord will use IN(value,other_value):

Model.where(:column => ["value", "other_value"]

outputs:

SELECT `table_name`.* FROM `table_name` WHERE `table_name`.`column` IN ('value', 'other_value')

This should achieve the equivalent of an OR on a single column

木格 2024-09-25 08:55:52

在Rails 3中,应该是

Model.where("column = ? or other_column = ?", value, other_value)

这也包括原始sql,但我不认为ActiveRecord中有一种方法可以进行OR操作。你的问题不是菜鸟问题。

Rails 5 添加了 or,因此现在在 Rails 版本高于5:

Model.where(column: value).or(Model.where(other_column: other_value))

这也处理 nil

in Rails 3, it should be

Model.where("column = ? or other_column = ?", value, other_value)

This also includes raw sql but I dont think there is a way in ActiveRecord to do OR operation. Your question is not a noob question.

Rails 5 added or, so this is easier now in an app with Rails version greater than 5:

Model.where(column: value).or(Model.where(other_column: other_value))

this handles nil values as well

自演自醉 2024-09-25 08:55:52

使用 ARel

t = Post.arel_table

results = Post.where(
  t[:author].eq("Someone").
  or(t[:title].matches("%something%"))
)

生成的 SQL:

ree-1.8.7-2010.02 > puts Post.where(t[:author].eq("Someone").or(t[:title].matches("%something%"))).to_sql
SELECT     "posts".* FROM       "posts"  WHERE     (("posts"."author" = 'Someone' OR "posts"."title" LIKE '%something%'))

Use ARel

t = Post.arel_table

results = Post.where(
  t[:author].eq("Someone").
  or(t[:title].matches("%something%"))
)

The resulting SQL:

ree-1.8.7-2010.02 > puts Post.where(t[:author].eq("Someone").or(t[:title].matches("%something%"))).to_sql
SELECT     "posts".* FROM       "posts"  WHERE     (("posts"."author" = 'Someone' OR "posts"."title" LIKE '%something%'))
止于盛夏 2024-09-25 08:55:52

Rails/ActiveRecord 的更新版本可能原生支持此语法。它看起来类似于:

Foo.where(foo: 'bar').or.where(bar: 'bar')

正如此拉取请求中所述 https://github.com/rails/rails /pull/9052

目前,只需坚持以下效果就很好:

Foo.where('foo= ? OR bar= ?', 'bar', 'bar')

更新: 根据 https://github.com/rails/rails/pull/16052 or 功能将在 Rails 5 中提供

更新: 功能已合并到 Rails 5 分支

An updated version of Rails/ActiveRecord may support this syntax natively. It would look similar to:

Foo.where(foo: 'bar').or.where(bar: 'bar')

As noted in this pull request https://github.com/rails/rails/pull/9052

For now, simply sticking with the following works great:

Foo.where('foo= ? OR bar= ?', 'bar', 'bar')

Update: According to https://github.com/rails/rails/pull/16052 the or feature will be available in Rails 5

Update: Feature has been merged to Rails 5 branch

鹤舞 2024-09-25 08:55:52

Rails 最近已将其添加到 ActiveRecord 中。它看起来将在 Rails 5 中发布。已承诺掌握:

https://github.com/rails /rails/commit/9e42cf019f2417473e7dcbfcb885709fa2709f89

Post.where(column: 'something').or(Post.where(other: 'else'))

# => SELECT * FROM posts WHERE (column = 'something') OR (other = 'else)

Rails has recently added this into ActiveRecord. It looks to be released in Rails 5. Committed to master already:

https://github.com/rails/rails/commit/9e42cf019f2417473e7dcbfcb885709fa2709f89

Post.where(column: 'something').or(Post.where(other: 'else'))

# => SELECT * FROM posts WHERE (column = 'something') OR (other = 'else)
著墨染雨君画夕 2024-09-25 08:55:52

Rails 5 附带了一个 or 方法。 (l文档链接

此方法接受 <代码>ActiveRecord::Relation 对象。例如:

User.where(first_name: 'James').or(User.where(last_name: 'Scott'))

Rails 5 comes with an or method. (link to documentation)

This method accepts an ActiveRecord::Relation object. eg:

User.where(first_name: 'James').or(User.where(last_name: 'Scott'))
我一直都在从未离去 2024-09-25 08:55:52

如果您想使用数组作为参数,以下代码可在 Rails 4 中使用:

query = Order.where(uuid: uuids, id: ids)
Order.where(query.where_values.map(&:to_sql).join(" OR "))
#=> Order Load (0.7ms)  SELECT "orders".* FROM "orders" WHERE ("orders"."uuid" IN ('5459eed8350e1b472bfee48375034103', '21313213jkads', '43ujrefdk2384us') OR "orders"."id" IN (2, 3, 4))

更多信息:OR 在 Rails 4 中使用数组作为参数的查询

If you want to use arrays as arguments, the following code works in Rails 4:

query = Order.where(uuid: uuids, id: ids)
Order.where(query.where_values.map(&:to_sql).join(" OR "))
#=> Order Load (0.7ms)  SELECT "orders".* FROM "orders" WHERE ("orders"."uuid" IN ('5459eed8350e1b472bfee48375034103', '21313213jkads', '43ujrefdk2384us') OR "orders"."id" IN (2, 3, 4))

More information: OR queries with arrays as arguments in Rails 4.

一念一轮回 2024-09-25 08:55:52

MetaWhere 插件非常棒。

轻松混合 OR 和 AND,连接任何关联的条件,甚至指定 OUTER JOIN!

Post.where({sharing_level: Post::Sharing[:everyone]} | ({sharing_level: Post::Sharing[:friends]} & {user: {followers: current_user} }).joins(:user.outer => :followers.outer}

The MetaWhere plugin is completely amazing.

Easily mix OR's and AND's, join conditions on any association, and even specify OUTER JOIN's!

Post.where({sharing_level: Post::Sharing[:everyone]} | ({sharing_level: Post::Sharing[:friends]} & {user: {followers: current_user} }).joins(:user.outer => :followers.outer}
昔日梦未散 2024-09-25 08:55:52

只需在条件中添加 OR 即可

Model.find(:all, :conditions => ["column = ? OR other_column = ?",value, other_value])

Just add an OR in the conditions

Model.find(:all, :conditions => ["column = ? OR other_column = ?",value, other_value])
哑剧 2024-09-25 08:55:52

使用rails + arel,更清晰的方式:

# Table name: messages
#
# sender_id:    integer
# recipient_id: integer
# content:      text

class Message < ActiveRecord::Base
  scope :by_participant, ->(user_id) do
    left  = arel_table[:sender_id].eq(user_id)
    right = arel_table[:recipient_id].eq(user_id)

    where(Arel::Nodes::Or.new(left, right))
  end
end

产生:

$ Message.by_participant(User.first.id).to_sql 
=> SELECT `messages`.* 
     FROM `messages` 
    WHERE `messages`.`sender_id` = 1 
       OR `messages`.`recipient_id` = 1

With rails + arel, a more clear way:

# Table name: messages
#
# sender_id:    integer
# recipient_id: integer
# content:      text

class Message < ActiveRecord::Base
  scope :by_participant, ->(user_id) do
    left  = arel_table[:sender_id].eq(user_id)
    right = arel_table[:recipient_id].eq(user_id)

    where(Arel::Nodes::Or.new(left, right))
  end
end

Produces:

$ Message.by_participant(User.first.id).to_sql 
=> SELECT `messages`.* 
     FROM `messages` 
    WHERE `messages`.`sender_id` = 1 
       OR `messages`.`recipient_id` = 1
权谋诡计 2024-09-25 08:55:52

你可以这样做:

Person.where("name = ? OR age = ?", 'Pearl', 24)

或更优雅的是,安装 rails_or gem 并执行以下操作:

Person.where(:name => 'Pearl').or(:age => 24)

You could do it like:

Person.where("name = ? OR age = ?", 'Pearl', 24)

or more elegant, install rails_or gem and do it like:

Person.where(:name => 'Pearl').or(:age => 24)
千仐 2024-09-25 08:55:52

我刚刚从客户工作中提取了这个插件,它可以让您将范围与.or结合起来。,例如。 Post.published.or.authored_by(current_user)。 Squeel(MetaSearch 的较新实现)也很棒,但不允许您使用 OR 范围,因此查询逻辑可能会有点冗余。

I just extracted this plugin from client work that lets you combine scopes with .or., ex. Post.published.or.authored_by(current_user). Squeel (newer implementation of MetaSearch) is also great, but doesn't let you OR scopes, so query logic can get a bit redundant.

诗化ㄋ丶相逢 2024-09-25 08:55:52

我想补充一下,这是一个搜索 ActiveRecord 的多个属性的解决方案。因为

.where(A: param[:A], B: param[:B])

将搜索 A 和 B。

I'd like to add this is a solution to search multiple attributes of an ActiveRecord. Since

.where(A: param[:A], B: param[:B])

will search for A and B.

甜心小果奶 2024-09-25 08:55:52

使用 activerecord_any_of gem,您可以编写

Book.where.any_of(Book.where(:author => 'Poe'), Book.where(:author => 'Hemingway')

Using the activerecord_any_of gem, you can write

Book.where.any_of(Book.where(:author => 'Poe'), Book.where(:author => 'Hemingway')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文