. where to find. ActiveRecord :: Relation NoMethodError

I am new to rails, and this may seem obvious, but I could not find the answer.

when i do

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

not working i keep getting

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

but if i changed

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

before

u = User.find_by_email(email_string)

I see that my changes are saved and the error does not occur.

So what I am missing. what .where returns a read-only object or something else?

+5
source share
1 answer

.where is actually a scope and really returns a collection of Users, not just one. You can get the first matching user (like .find_by_email) with

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

Alternatively, you can return the collection with

User.find_all_by_email(email_string)

Hope this helps.

+17

All Articles