ActiveRecord where field = ? array of possible values

Ruby on-RailsRails Activerecord

Ruby on-Rails Problem Overview


I want to do

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

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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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

Solution 4 - Ruby on-Rails

You can use the 'in' operator:

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

Solution 5 - Ruby on-Rails

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

Solution 6 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionquantumpotatoView Question on Stackoverflow
Solution 1 - Ruby on-RailsWill RichardsonView Answer on Stackoverflow
Solution 2 - Ruby on-RailsmessanjahView Answer on Stackoverflow
Solution 3 - Ruby on-RailsSelfishView Answer on Stackoverflow
Solution 4 - Ruby on-RailsAhmad MOUSSAView Answer on Stackoverflow
Solution 5 - Ruby on-RailsPrithviraj PillaiView Answer on Stackoverflow
Solution 6 - Ruby on-RailsmmsilviuView Answer on Stackoverflow