ActiveRecord where field = ? 可能值的数组

我想做的事

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

如果不将或语句连接在一起,我如何完成这个查询?

87362 次浏览

From here it appears to be done using an SQL in statement:

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

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

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

From the ActiveRecord Query Interface guide

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

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

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:

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

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

There is a 'small' difference between where and find_by.

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

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.

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

meanwhile where it 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])

You can use the 'in' operator:

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