112

I want to do

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

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

0

6 Answers 6

213

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])
Sign up to request clarification or add additional context in comments.

5 Comments

This can be simplified to Model.where(id: [array of values])
Model.where("id in (?)", [1..8]) does not seemt o be working for me. any ideas?
You don't need the square brackets, 1..8 is already array-like.
Will this syntax automatically escape single quotes within the [array of values]?
When my array is big enough, the method expend a lot of time. How could you do that with really big arrays?
23

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])

1 Comment

The link in this answer is currently not working, should be guides.rubyonrails.org/…
7

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])

2 Comments

find_by actually is where().take. Model.find_by(id: [1, 2, 3]) will only return Model(id: 1)
another option if looking for just a single record instead of the array that meets the criteria, find_by_id([1, 2, 3])
4

You can use the 'in' operator:

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

Comments

0

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

Comments

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.