Reputation: 1663
In Rails document,I find that:
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
But when I execute this command,I got
ActiveRecord::RecordNotFound: Couldn't find all Persons with IDs (1, 2, 6)
(found 1 results, but was looking for 2)
How I got this error? My Rails version is 3.2.14
Upvotes: 0
Views: 123
Reputation: 14943
find
expects to find all records, if one is missing you will get RecordNotFound
If you want it to work without erroring when ids are missing use
Person.where("id in (1,2,6)")
Upvotes: 1
Reputation: 8498
The error points out that there are no records in Person
with the id
s 1
, 2
and 6
.
The syntax Person.find([1,2,6])
and Person.find(1, 2, 6)
is equivalent and correct to retrieve multiple records by id. Please have a look into the API documentation.
Maybe you check what is into the table. Start a irb
-shell of your project and print all records of Person
by writing: Person.all
I cannot find find_all_by
in the newest API documentation and the argumentation is wrong that find
raises a RecordNotFound
exception. It raises an RecordNotFound
if none of the id's were found. The documentation says to find
:
If no record can be found for all of the listed ids, then RecordNotFound will be raised.
See also here.
Upvotes: 1
Reputation: 1315
I believe the correct syntax for pulling multiple id's at once is Person.find([1,2,6])
. If this still returns ActiveRecord::RecordNotFound
then the records with those id's don't exist.
In order to get around the error for if an id does not exist, you can do Person.find_all_by_id([1,2,6])
. In this case, if it doesn't find records it should return an empty array.
Hope this helps.
Upvotes: 1