user.attributes[:email] and user.email

T

tom

Hi

Could somebody explain to me why the following doesn't work:

@user = User.find:)first)
@user.attributes[:email] = params[:user][:email] # this does nothing!!
@user.save

but the following DOES work...

@user = User.find:)first)
@user.email = params[:user][:email] # this works like it should?!
@user.save

I only realized this when the @user.update_attributes(params[:user])
didn't seem to do anything. I was under the impression that the two
snippets above did the same thing?

Does anybody else have this problem with @user.update_attributes??

Thanks in advance

Tom Medhurst
 
L

loidee

the reason is because the @user has a variable defined as email but not
a variable of type array or hash, named attributes. I hope this helps,
if not let me know
 
T

tom

I probably should have mentioned that @user is a class that inherits
from ActiveRecord::Base.
so the attributes hash *should* be wired up the same as the
accessors..?
the @user.update_attributes was a line code-gen'ed by rails so why
wouldn't it work?
 
C

Codemonk

Because attributes creates a copy of the current values stored in a
hash, while when you assign the attribute directly you are changing the
value itself.

@user.attributes # This copies all of the current values of the @user
object into a hash
@user.attribute_name # is the actual value stored on the user object.

@user.attributes does NOT return a pointer to the underlying attributes
hash
 
L

loidee

i figured it was inherited from active record but i think codemonk
explains it quite well. i suppose the fact that there is a method
#update_attributes can be misleading and cause one to expect an actual
attributes hash
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top