简体   繁体   English

ActiveRecord的方法不暗示数据库或转换为哈希/数组

[英]Methods for ActiveRecord that not implies database or convert into Hash/Array

I have a model foo and in my index action I do: 我有一个模型foo,并在索引操作中执行:

@foos = foo.all 

and now, on the view I want to know if this @foos contain a record whit foo.id = whatever 现在,在视图上,我想知道此@foos包含一条记录,其中foo.id = whatever

One method of do that is @foos.exists?(id: whatever) , but this method implies a bd query and I want avoid this. 一种做到这一点的方法是@foos.exists?(id: whatever) ,但是该方法暗含bd查询,我想避免这种情况。

Other method will be @foos.collect(&:id).include?(whatever) but this implies the conversion of all @foos into array, another case that I would avoid. 其他方法将是@foos.collect(&:id).include?(whatever)但这意味着将所有@foos转换为数组,我会避免这种情况。

There are another ways to accomplish it? 还有另一种方法可以实现吗?

Thanks in advance 提前致谢

UPDATE UPDATE

I want also get this object not only know if exists, sorry for bad explanation. 我也想让这个对象不仅知道是否存在,对不起错误的解释。

You can use the Enumerable#any? 您可以使用Enumerable#any吗? to check if the value exists in the array of results: 检查值是否存在于结果数组中:

@foos.any? { |foo| foo.id == whatever }

This check will be performed on the result array without hitting the database again and without converting the array to another structure. 将对结果数组执行此检查,而无需再次访问数据库,也不会将数组转换为其他结构。

UPDATE UPDATE

If you want the object returned, use Enumerable#find , like this: 如果要返回对象,请使用Enumerable#find ,如下所示:

@foos.find { |foo| foo.id == whatever }

This will return the first occurrence where foo.id == whatever . 这将返回第一个匹配项foo.id == whatever

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM