Rails Console find users by array of ids Rails Console find users by array of ids ruby ruby

Rails Console find users by array of ids


For an array, you can use one of these:

# Will raise exception if any value not foundUser.find( [1,3,5] )# Will not raise an exceptionUser.find_all_by_id( [1,3,5] ) # Rails 3User.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 foundUser.find((1..4).to_a)   #same as User.find([1,2,3,4])# Will not raise an exceptionUser.find_all_by_id(1..4)  # Rails 3User.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.


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.