.where vs find.ActiveRecord :: Relation NoMethodError

use*_*005 5 activerecord ruby-on-rails-3

我是铁杆的新手,这似乎很明显,但找不到答案.

当我做

u = User.where("email=?", email_string)
u.name = "new name" 
Run Code Online (Sandbox Code Playgroud)

我不断工作不起作用

NoMethodError: undefined method `name=' for #<ActiveRecord::Relation:0x1049c2890> 
Run Code Online (Sandbox Code Playgroud)

但如果我改变

u = User.where("email=?", email_string)
Run Code Online (Sandbox Code Playgroud)

u = User.find_by_email(email_string)
Run Code Online (Sandbox Code Playgroud)

我可以看到我的更改被持久化并且没有抛出任何错误.

所以我错过了什么.是吗.where返回一个只读对象或什么?

mor*_*itz 17

.where实际上是一个范围,确实返回了一组用户,而不是一个用户.您可以使用获取第一个匹配的用户(如.find_by_email)

User.where('email = ?', email_string).first
Run Code Online (Sandbox Code Playgroud)

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

User.find_all_by_email(email_string)
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助.