【问题标题】:Rails 4.2.11, User.find_by(name: 'name', email: 'email') returning array, not instanceRails 4.2.11,User.find_by(name: 'name', email: 'email') 返回数组,而不是实例
【发布时间】:2021-04-27 14:47:54
【问题描述】:

在 Rails 4.2.11 中,

User.find_by(name: 'name', email: 'email')

返回一个ActiveRecord::Relation(包含一个用户实例的数组)而不是一个用户实例。

#<ActiveRecord::Relation [#<User id: 1, name: "Tester Test", email: "stester@xxx.xxx", created_at: "2021-04-27 14:08:49", updated_at: "2021-04-27 14:08:49">]>

This is happening in the context of a failing cucumber test where I create an authorization record and a user record.  The authorization record is found, but the user record comes back only as a Relation no matter what I do.  Tried .first, .take, several other ways to retrieve the instance.

这与User.where 的输出相同,而不是User.find_by。知道为什么会这样吗???

【问题讨论】:

    标签: ruby-on-rails-4 activerecord


    【解决方案1】:

    如果您添加“.first”,例如: User.find_by(name: 'name', email: 'email').first 适合你吗?

    【讨论】:

    • 我尝试了很多东西,包括添加 .first(这可能是我想到的“第一”件事)和 .take 以及其他一些构造。返回完全相同的结果。我以前使用过 find-by 来获取某物的一个实例。无法弄清楚发生了什么。
    【解决方案2】:

    在我停止运行测试大约 10 分钟后,现在一切正常。我唯一的解释是,当我的互联网出现故障时,我当前的代码与我的 ide 终端认为它看到的代码之间有时似乎存在差异。

    我最初使用where 只是为了了解它是否正常工作(向自己表明它只会返回一个有效记录)。然后我将它修改为find_by(我真正想要的),但它继续返回结果,好像where 仍然存在一样。然后,宾果游戏开始按预期运行。 ???

    我唯一的解释是这些间歇性中断正在影响我 ide 的互联网连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2011-02-07
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多