110

I want to do

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

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

quantumpotato
  • 9,637
  • 14
  • 70
  • 146

6 Answers6

207

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])
Community
  • 1
  • 1
Will Richardson
  • 7,780
  • 7
  • 42
  • 56
22

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])
messanjah
  • 8,977
  • 4
  • 27
  • 40
  • The link in this answer is currently not working, should be https://guides.rubyonrails.org/active_record_querying.html#subset-conditions – kangkyu Apr 25 '19 at 01:33
6

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])
Selfish
  • 6,023
  • 4
  • 44
  • 63
  • 1
    `find_by` actually is `where().take`. `Model.find_by(id: [1, 2, 3])` will only return `Model(id: 1)` – James.Oliver Jun 07 '19 at 01:20
  • another option if looking for just a single record instead of the array that meets the criteria, `find_by_id([1, 2, 3])` – Steve Apr 27 '20 at 21:26
3

You can use the 'in' operator:

Model.in(id: [array of values])
Ahmad MOUSSA
  • 2,729
  • 19
  • 31
0

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

0

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])
mmsilviu
  • 1,211
  • 15
  • 25