views:

1369

answers:

3

When I have array of ids, like

ids = [2,3,5]

and I perform

Comment.find(ids)

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

current_user.comments.find(ids)

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?

+3  A: 

To avoid exceptions killing your app you should catch those exceptions and treat them the way you wish, defining the behavior for you app on those situations where the id is not found.

begin
  current_user.comments.find(ids)
rescue
  #do something in case of exception found
end

Here's more info on exceptions in ruby.

rogeriopvl
yep this solves the problem, but it's not really a clean solution
Darth
+14  A: 

If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.

Comment.find_all_by_id([2, 3, 5])

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

user.comments.find_all_by_id(potentially_nonexistent_ids)

case as well.

kaleidomedallion
this is my preferred solution, it seems cleaner than the exception handling route
Sam Saffron
As another extension to this, should you need to chain complex conditions, you could even do Comment.all(:conditions => ["approved and id in (?)", [1,2,3]])
Omar Qureshi
A: 

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

mtfk