Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid ActiveRecord::RecordNotFound exceptions when querying multiple records

I have this code:

Article.find([1,2,3])

But only record 1 and 2 exist in the database. I get this exception:

"ActiveRecord::RecordNotFound (Couldn't find all Offers with IDs (1,2,3) (found 2 results, but was looking for 3))"

Is there a way to only get the existing records and not the exception?

like image 435
remi Avatar asked Oct 18 '10 17:10

remi


2 Answers

Article.find_all_by_id([1,2,3]) is the way to go!

like image 147
remi Avatar answered Oct 23 '22 09:10

remi


Rails 3+, ruby 1.9+ way:

Article.where(id: [1,2,3])
like image 39
DGM Avatar answered Oct 23 '22 10:10

DGM