findind all using .all vs. where

六眼飞鱼酱① 提交于 2019-12-08 09:33:36

问题


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

I get an error

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

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

Enumeration.where(false).find(107)

where this does not work

Enumeration.all.find(107)

Can someone explain to me how this works?

Thanks


回答1:


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 

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: "...">

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: "..."> 


来源:https://stackoverflow.com/questions/11610942/findind-all-using-all-vs-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!