Rails Console find users by array of ids

MysqlRuby on-RailsRubyPostgresqlRails Console

Mysql Problem Overview


So I have an array of user ids. Is there a way in rails console to query all of these user's with the array

something like

ids = [1, 2, 3, 4]

users = User.find(ids)

and have it return all 4 users?

Mysql Solutions


Solution 1 - Mysql

For an array, you can use one of these:

# Will raise exception if any value not found
User.find( [1,3,5] )

# Will not raise an exception
User.find_all_by_id( [1,3,5] ) # Rails 3
User.where(id: [1,3,5])        # Rails 4

If you happen to be using a range, you can use these:

# Will raise exception if any value not found
User.find((1..4).to_a)   #same as User.find([1,2,3,4])

# Will not raise an exception
User.find_all_by_id(1..4)  # Rails 3
User.where(id: 1..4)       # Rails 4

As @diego.greyrobot notes in a comment, a range causes a SQL BETWEEN clause, whereas an array causes a SQL IN clause.

Don't use User.find_by_id() -- It will only return one record, no matter how may IDs you pass in.

Solution 2 - Mysql

you can use User.where(id: ids)

Solution 3 - Mysql

Use splash operator:

ids = [1, 2, 3, 4]

users = User.find(*ids)

Note that it will raise an exception if it fails to find any of the users.

Solution 4 - Mysql

This is work for me...

ids = [1, 2, 3, 4]

users = User.find(ids)

users = User.find(*ids)

users = User.find_all_by_id(ids)

All are working..

Solution 5 - Mysql

you can use

   Users.where({ id: [1,2,3 ,4]})
 # SELECT * FROM users WHERE id IN (1,2,3,4)
   

Solution 6 - Mysql

What you're doing is supposed to work when all the ids exist.

The reason you might be seeing an exception is because at least one of those ids does not exist in the database.

Instead, you want to use find_all_by_id if you don't want to get an exception:

User.find_all_by_id([1, 2, 3, 4])

# Does the following sql:    
User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` IN (1, 2, 3, 4)

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
QuestionSethView Question on Stackoverflow
Solution 1 - MysqlGrant BirchmeierView Answer on Stackoverflow
Solution 2 - MysqlNitin JainView Answer on Stackoverflow
Solution 3 - MysqlBroiSatseView Answer on Stackoverflow
Solution 4 - MysqlDheerView Answer on Stackoverflow
Solution 5 - MysqlTarek SaiedView Answer on Stackoverflow
Solution 6 - MysqlAbdoView Answer on Stackoverflow