什么是相当于" find_all_by_id"在轨道4 [英] what is the equivalent of "find_all_by_id" in rails 4

查看:132
本文介绍了什么是相当于" find_all_by_id"在轨道4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想从数据库中找到各自的记录,采用主动记录查询ID数组。例如:的id = [2,3,1]

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]

现在,对我来说,找到其ID是其中的一个阵列中,在低版本的Rails的特定型号的所有记录,我想我可以做这样的事情:

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])

但根据这个帖子

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做到这一点,而不必包括宝石?

My question is that is there no way I can do this in rails4.2 without necessarily having to include a gem?

感谢。

推荐答案

直接更换的 find_by 。您可以使用它,如:

The direct replacement is find_by. You can use it like:

Model.find_by(id: [2, 3, 1])

这是真的去precated是有方法的名称的属性部分的唯一的事。

The only thing that is really deprecated is having the attribute part of the method name.

在code是非常相似的href="https://github.com/rails/activerecord-de$p$pcated_finders" rel="nofollow">提出的替代的 Model.where(编号:[2,3,1),你可以看到:

The code is very similar to the proposed alternative of Model.where(id: [2, 3, 1]) as you can see:

def find_by(*args)
  where(*args).take
end

请注意,建议(现已删除) Model.find([2,3,1)不可以相同,那么将抛出一个异常,如果阵列中的任何入侵检测系统是不存在的。

Please note that 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.

这篇关于什么是相当于" find_all_by_id"在轨道4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆