Find( [1,2,3] ) find from array without raising error

Hello!

Best way to explain this is with some code…

id_arr = [1,2,3,4,5] # There is no record with id 5.
=>
results = find(id_arr)
ActiveRecord::RecordNotFound: Couldn’t find all Posts with IDs
(1,2,3,4,5).

From reading the documentation it appears that AR will produce this
error if ALL the ids do not return errors, but it appears to error when
one or more of the ids does not return.

Any way to get those id’s which do exist to return, without the error?

Cheers.

Douglas F Shearer
[email protected]

Douglas S. wrote:

From reading the documentation it appears that AR will produce this
error if ALL the ids do not return errors, but it appears to error when
one or more of the ids does not return.

Any way to get those id’s which do exist to return, without the error?

From memory (I don’t remember if you need something like
id_arr.join(’,’) in the conditions instead of just id_arr):

results = id_arr.empty? ? [] : find(:all, :conditions => [ ‘id IN (?)’,
id_arr ])

Lionel

Lionel B. wrote:

results = id_arr.empty? ? [] : find(:all, :conditions => [ ‘id IN (?)’,
id_arr ])

find(:all) seems to be the way to go, came up with the following just
after I posted…

find(:all, :conditions => 'id = ’ + id_arr.inject{ |sum,i| sum.to_s + ’
OR id = ’ + i.to_s })

… but yours is far cleaner, I think I shall go with that.

Cheers.

Douglas F Shearer
[email protected]

Nicer to do:

Thing.find(:all, :conditions => [‘id IN (?)’, id_arr])

On Aug 29, 8:10 pm, Douglas S. [email protected]

On 8/29/07, Douglas S. [email protected] wrote:

From reading the documentation it appears that AR will produce this
error if ALL the ids do not return errors, but it appears to error when
one or more of the ids does not return.

Any way to get those id’s which do exist to return, without the error?

There may be an easier way, but something like this will do it:

results = id_arr.collect {|i| Model.find_by_id(i)}.compact

or, more efficient, since it makes only one query:

results = Model.find :all, :conditions => [“id in (#{id_arr.collect
{‘?’}.join(‘,’)})”, *id_arr]

On 8/29/07, andrewbruce [email protected] wrote:

Nicer to do:

Thing.find(:all, :conditions => [‘id IN (?)’, id_arr])

Hmm, I didn’t know that an array was automagically expanded in a
parameter list like that. Handy, and much cleaner than my line noise
:~)

andrewbruce wrote:

Thing.find(:all, :conditions => [‘id IN (?)’, id_arr])

Great minds think alike! Nice to get confirmation that my (Slightly late
relative to my original posting) idea is correct.

Thanks guys! :o)

Douglas F Shearer
[email protected]

Bob S. wrote:

But depending on the context you can have to test for id_arr.empty? …