remi
remi

Reputation: 1303

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?

Upvotes: 14

Views: 7274

Answers (3)

DGM
DGM

Reputation: 26979

Rails 3+, ruby 1.9+ way:

Article.where(id: [1,2,3])

Upvotes: 13

BaroqueBobcat
BaroqueBobcat

Reputation: 10150

The problem is that using find with ids raises exceptions when the records are missing. You could try something like

Article.all :conditions => ["id in (?)", [1,2,3]]

or more succinctly

Article.find_all_by_id [1,2,3]

using find :all does not raise errors on missing records, so even if the records are missing you are cool.

Upvotes: 4

remi
remi

Reputation: 1303

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

Upvotes: 22

Related Questions