Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the equivalent of "find_all_by_id" in rails 4

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.

like image 765
x6iae Avatar asked Aug 06 '15 22:08

x6iae


2 Answers

This should work:

array_of_ids = [2,3,1]
Model.where(id: array_of_ids)
like image 68
kjmagic13 Avatar answered Sep 19 '22 10:09

kjmagic13


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.

like image 26
Brad Werth Avatar answered Sep 21 '22 10:09

Brad Werth