gpt4 book ai didi

ruby-on-rails-3 - 查找所有使用 .all 与 where

转载 作者:行者123 更新时间:2023-12-04 18:16:22 27 4
gpt4 key购买 nike

在我的 Controller 中,我将所有条目从这样的表中获取

@enums = Enuemerations.all

然后我想通过做搜索并从中获取名称
@enums.find(107).name

我收到一个错误
undefined method `name' for #<Enumerator:0xb5eb9d98>

所以我在 rails 控制台试了一下,发现这个工作
Enumeration.where(false).find(107)

这不起作用
Enumeration.all.find(107)

有人可以向我解释这是如何工作的吗?

谢谢

最佳答案

使用 Enumeration.all立即查询返回 Array 的数据库与所有枚举记录(如果您只想要一条记录,这将是非常低效的)。它不再知道 ActiveRecord 方法:

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

调用 findArray使用 Enumerable#find 这将需要不同的语法,例如:
enums = Enumeration.all
enum = enums.find { |e| e.id == 2 }
=> #<Enumeration id: 2, name: "...">

使用 Enumeration.where(false)只返回一个懒惰的 ActiveRecord::Relation ,它实际上并没有命中数据库(还),这允许您链接额外的 ActiveRecord 方法,例如 find在你上面的例子中。
> 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: "...">

关于ruby-on-rails-3 - 查找所有使用 .all 与 where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11610942/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com