Which is equivalent to "find_all_by_id" in rails 4

I have an array of identifiers that I want to find their corresponding records from the database using the active record query. for example: ids = [2, 3, 1]

Now, for me, to find all the records of a particular model, whose identifier is one of the elements in the array. In lower versions of rails, I think 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 I cannot do this in rails4.2 without having to include a gem?

Thanks.

+7
ruby-on-rails activerecord ruby-on-rails-4
source share
2 answers

officially proposed alternative to 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] 

Note:

The proposed (now deleted) Model.find([2, 3, 1]) is not equivalent, it throws an exception if there are no identifiers in it.

Similarly, the proposed (now edited) Model.find_by(id: [2, 3, 1]) is not equivalent, it returns only one result.

+3
source share

This should work:

 array_of_ids = [2,3,1] Model.where(id: array_of_ids) 
+7
source share

All Articles