gpt4 book ai didi

ruby-on-rails - RoR 从 ActiveRecord::Relation 中获取属性

转载 作者:数据小太阳 更新时间:2023-10-29 07:32:01 24 4
gpt4 key购买 nike

我是 RoR 的新手。请告诉我如何从 ActiveRecord::Relation 获取属性?例如我写:

@user = User.where(code: 123)

接下来我要获取属性id

id = @user.id

但是这个方法行不通。提前致谢

最佳答案

当使用 .where 时,它会给你一个 active record relation所以你不能直接在它上面找到 id 因为它是一个关系而不是一个单一的模型对象。

修复:

你可以做到

@user = User.where(code: 123).first

您可以使用 dynamic finders

@user = User.find_by_code(123)

关于ruby-on-rails - RoR 从 ActiveRecord::Relation 中获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25683534/

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