。凡vs寻找。 ActiveRecord的::关系NoMethodError [英] .where vs find. ActiveRecord::Relation NoMethodError

查看:136
本文介绍了。凡vs寻找。 ActiveRecord的::关系NoMethodError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的轨道,这似乎是显而易见的,但找不到答案。

I'm new to rails and this might seem obvious, but couldn't find a answer.

当我这样做

u = User.where("email=?", email_string)
u.name = "new name" 

不工作,我不断收到

doesn't work i keep getting

NoMethodError: undefined method `name=' for #<ActiveRecord::Relation:0x1049c2890> 

但如果我改变

but if i change

u = User.where("email=?", email_string)

u = User.find_by_email(email_string)

我可以看到我的变化正在持续并且没有错误抛出。

i can see my changes being persisted and no error thrown.

所以,我在想什么。难道是。凡返回一个只读对象或东西吗?

So what am i missing. is it that .where returns a read only object or something ?

推荐答案

。凡实际上是一个范围,实际上返回用户的集合,而不是单一的。您可以获取第一个匹配的用户(如.find_by_email一样)与

.where is actually a scope and indeed returns a collection of Users and not a single one. You can obtain the first matching user (as .find_by_email does) with

User.where('email = ?', email_string).first

此外,你可以返回一个集合以

Additionally, you can return a collection with

User.find_all_by_email(email_string)

我希望这有助于。

I hope this helps.

这篇关于。凡vs寻找。 ActiveRecord的::关系NoMethodError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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