[ruby-on-rails] How to select where ID in Array Rails ActiveRecord without exception

2 Answers

Update: This answer is more relevant for Rails 4.x

Do this:

current_user.comments.where(:id=>[123,"456","Michael Jackson"])

The stronger side of this approach is that it returns a Relation object, to which you can join more .where clauses, .limit clauses, etc., which is very helpful. It also allows non-existent IDs without throwing exceptions.

The newer Ruby syntax would be:

current_user.comments.where(id: [123, "456", "Michael Jackson"])

When I have array of ids, like

ids = [2,3,5]

and I perform


everything works fine. But when there is id that doesn't exist, I get an exception. This occurs generaly when I get list of IDs that match some filter and than I do something like


This time I may have a valid comment ID, which however does not belong to given User, so it is not found and I get an exception.

I've tried find(:all, ids), but it returns all of the records.

The only way I can do it now is

current_user.comments.select { |c| ids.include?(c.id) }

But that seems to me like super inefficient solution.

Is there better way to select ID in Array without getting exception on non-existing record?

Now .find and .find_by_id methods are deprecated in rails 4. So instead we can use below:

Comment.where(id: [2, 3, 5])

It will work even if some of the ids don't exist. This works in the

user.comments.where(id: avoided_ids_array)

Also for excluding ID's

Comment.where.not(id: [2, 3, 5])

You can also use it in named_scope if You want to put there others conditions

for example include some other model:

named_scope 'get_by_ids', lambda { |ids| { :include => [:comments], :conditions => ["comments.id IN (?)", ids] } }