我有一组id,我想使用活动记录查询从数据库中找到它们各自的记录.例如:ids = [2,3,1]
现在,让我找到一个特定模型的所有记录,其id是数组中的一个,在较低版本的rails中,我想我可以做类似的事情:
Model.find_all_by_id([2,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?
谢谢.
解决方法
officially proposed alternative是Model.where(id:[2,1]).
# There are 3 users in the db,with ids 1,2,and 3 > User.where(id: [1,4,1234]).pluck(:id) sql (2.5ms) SELECT `users`.`id` FROM `users` WHERE `users`.`id` IN (1,1234) => [1,3]
请注意:
建议的(现在删除的)Model.find([2,1])不等效,如果数组中的任何id不存在,它将抛出异常.
类似地,建议的(现在已编辑)Model.find_by(id:[2,它只返回一个结果.