Ruby-on-rails ActiveRecord where field = ? 可能值的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28954500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:06:45  来源:igfitidea点击:

ActiveRecord where field = ? array of possible values

ruby-on-railsrails-activerecord

提问by quantumpotato

I want to do

我想要做

Model.where('id = ?', [array of values])

How do I accomplish this look up without chaining OR statements together?

如何在不将 OR 语句链接在一起的情况下完成此查找?

回答by Will Richardson

From hereit appears to be done using an SQL instatement:

这里开始,它似乎是使用 SQLin语句完成的:

Model.where('id IN (?)', [array of values])

Or more simply, as kdeisz pointed out (Using Arel to create the SQL query):

或者更简单,正如 kdeisz 指出的(使用 Arel 创建 SQL 查询):

Model.where(id: [array of values])

回答by messanjah

From the ActiveRecord Query Interface guide

来自ActiveRecord 查询接口指南

If you want to find records using the IN expression you can pass an array to the conditions hash:

如果要使用 IN 表达式查找记录,可以将数组传递给条件哈希:

Client.where(orders_count: [1,3,5])

回答by Selfish

For readability, this can be simplified even further, to:

为了可读性,这可以进一步简化为:

Model.find_by(id: [array of values])

This is equivalent to using where, but more explicit:

这相当于 using where,但更明确:

Model.where(id: [array of values])

回答by BinaryMan

You can use the 'in' operator:

您可以使用“in”运算符:

Model.in(id: [array of values])

回答by Prithviraj Pillai

If you are looking for a query in mongoid this is the oneModel.where(:field.in => ["value1", "value2"] ).all.to_a

如果您正在寻找 mongoid 中的查询,这就是Model.where(:field.in => ["value1", "value2"] ).all.to_a

回答by mmsilviu

There is a 'small' difference between whereand find_by.

wherefind_by之间存在“小”差异。

find_bywill return just one record if found otherwise it will be nil.

如果找到,find_by将只返回一条记录,否则它将为零。

Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself. If no record is found, returns nil.

查找与指定条件匹配的第一条记录。没有隐含的顺序,所以如果顺序很重要,你应该自己指定。如果没有找到记录,则返回 nil。

  def find_by(*args)
      where(*args).take
    rescue RangeError
      nil
  end

meanwhile whereit will return an relation

同时在那里它将返回一个关系

Returns a new relation, which is the result of filtering the current relation according to the conditions in the arguments.

返回一个新的关系,它是根据参数中的条件过滤当前关系的结果。

So, in your situation the appropriate code is:

因此,在您的情况下,适当的代码是:

Model.where(id: [array of values])