相当于" find_all_by_id"在铁轨4

时间:2015-08-06 22:51:51

标签: ruby-on-rails ruby-on-rails-4 activerecord

我有一个id数组,我想使用活动记录查询从数据库中找到它们各自的记录。例如:ids = [2, 3, 1]

现在,让我找到特定模型的所有记录,其id是数组中的一个,在较低版本的rails中,我想我可以做类似的事情:

Model.find_all_by_id([2, 3, 1])

但根据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

我的问题是,我无法在rails4.2中执行此操作而无需包含gem?

感谢。

2 个答案:

答案 0 :(得分:7)

这应该有效:

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

答案 1 :(得分:4)

officially proposed alternativeModel.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不存在,则会抛出异常。

同样,建议(现已编辑完毕)Model.find_by(id: [2, 3, 1]) 等效,只返回一个结果。