Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.where vs find. ActiveRecord::Relation NoMethodError

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 ?

like image 360
user368005 Avatar asked Sep 16 '11 09:09

user368005


1 Answers

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

like image 133
moritz Avatar answered Oct 21 '22 06:10

moritz