rails 4中的“find_all_by_id”等价物
我有一组id,我想使用活动记录查询从数据库中找到它们各自的记录。 例如: ids = [2, 3, 1]
现在,让我找到一个特定模型的所有记录,其id是数组中的一个,在较低版本的rails中,我想我可以做类似的事情:
Model.find_all_by_id([2, 3, 1])
但根据这篇文章 ,
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
我的问题是,我无法在rails4.2中执行此操作而无需包含gem?
谢谢。
官方提出的替代方案是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]
请注意:
建议的(现在删除的) Model.find([2, 3, 1])
不等效,如果数组中的任何id不存在,它将抛出exception。
类似地,建议的(现在已编辑) Model.find_by(id: [2, 3, 1])
不等效,它只返回一个结果。
这应该工作:
array_of_ids = [2,3,1] Model.where(id: array_of_ids)