I have an array of ids that I want to find their respective records from the database, using active record query. e.g: ids = [2, 3, 1]
now, for me to find all records of a particular model whose id is one of those in the array, In lower versions of rails, I guess I can do something like:
Model.find_all_by_id([2, 3, 1])
but according to this post,
These methods were deprecated on 4.0 and removed at 4.1. If you want to
keep sing then you need to include this gem
https://github.com/rails/activerecord-deprecated_finders
My question is that is there no way I can do this in rails4.2 without necessarily having to include a gem?
Thanks.
This should work:
array_of_ids = [2,3,1]
Model.where(id: array_of_ids)
The officially proposed alternative is Model.where(id: [2, 3, 1])
.
# There are 3 users in the db, with ids 1, 2, and 3
> User.where(id: [1,2,3,4,1234]).pluck(:id)
SQL (2.5ms) SELECT `users`.`id` FROM `users` WHERE `users`.`id` IN (1, 2, 3, 4, 1234)
=> [1, 2, 3]
Please note:
The suggested (now deleted) Model.find([2, 3, 1])
is not equivalent, it will throw an exception if any ids in the array do not exist.
Similarly, the suggested (now edited away) Model.find_by(id: [2, 3, 1])
is not equivalent, it only return one result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With