.where vs find. ActiveRecord::Relation NoMethodError

↘锁芯ラ 提交于 2019-12-10 14:53:13

问题


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

when i do

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)

to

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 ?


回答1:


.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.



来源:https://stackoverflow.com/questions/7442791/where-vs-find-activerecordrelation-nomethoderror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!