what is the equivalent of “find_all_by_id” in rails 4

大城市里の小女人 提交于 2019-12-09 17:08:42

问题


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.


回答1:


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.




回答2:


This should work:

array_of_ids = [2,3,1]
Model.where(id: array_of_ids)


来源:https://stackoverflow.com/questions/31867062/what-is-the-equivalent-of-find-all-by-id-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!