findind全部使用.all vs.where [英] findind all using .all vs. where

查看:101
本文介绍了findind全部使用.all vs.where的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我从这样的表格中获取所有条目

In my controller i am getting all entries form a table like this

@enums = Enuemerations.all

然后,我想搜索并通过这样做获得名称

Then later i want to search and get the name from by doing

@enums.find(107).name

我收到错误

undefined method `name' for #<Enumerator:0xb5eb9d98>

所以我在Rails控制台中进行了尝试,发现它可以正常工作

So I tried it out in the rails console and found this working

Enumeration.where(false).find(107)

这不起作用

Enumeration.all.find(107)

有人可以向我解释它的工作原理吗?

Can someone explain to me how this works?

谢谢

推荐答案

使用 Enumeration.all 立即查询数据库,并返回 Array 包含所有的枚举记录(如果您只想要一个记录,则效率很低)。它不再知道ActiveRecord方法:

Using Enumeration.all instantly queries the database returning an Array with all the Enumeration records (if you only want a single record this would be very inefficient). It no longer knows about the ActiveRecord methods:

 > Enumeration.all.class
  Enumeration Load (0.1ms)  SELECT "enumerations".* FROM "enumerations" 
 => Array 

在<$ c上调用查找 $ c> Array 使用 Enumerable#find ,这将需要不同的语法,例如:

Calling find on an Array uses Enumerable#find which would need a different syntax, e.g:

enums = Enumeration.all
enum = enums.find { |e| e.id == 2 }
 => #<Enumeration id: 2, name: "...">






使用 Enumeration.where (false)仅返回一个懒惰的 ActiveRecord :: Relation ,它实际上并未访问数据库(尚未),这使您可以链接更多ActiveRecord方法,例如上面示例中的 find


Using Enumeration.where(false) only returns a lazy ActiveRecord::Relation, it doesn't actually hit the database (yet), this allows you to chain extra ActiveRecord methods such as find in your example above.

> Enumeration.where(false).class
 => ActiveRecord::Relation 

> Enumeration.where(false).find(2)
  Enumeration Load (0.2ms)  SELECT "enumerations".* FROM "enumerations" WHERE "enumerations"."id" = ? LIMIT 1  [["id", 2]]
 => #<Enumeration id: 2, name: "..."> 

这篇关于findind全部使用.all vs.where的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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