user.attributes[:email] and user.email

Discussion in 'Ruby' started by tom@tmedhurst.co.uk, May 26, 2006.

  1. Guest

    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
     
    , May 26, 2006
    #1
    1. Advertising

  2. loidee Guest

    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
     
    loidee, May 26, 2006
    #2
    1. Advertising

  3. Guest

    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?
     
    , May 26, 2006
    #3
  4. Codemonk Guest

    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
     
    Codemonk, May 26, 2006
    #4
  5. loidee Guest

    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
     
    loidee, May 27, 2006
    #5
  6. Guest

    thanks for the info!
     
    , May 28, 2006
    #6
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    2
    Views:
    5,928
  2. Max
    Replies:
    1
    Views:
    497
    Joe Kesselman
    Sep 22, 2006
  3. P4trykx
    Replies:
    2
    Views:
    1,843
    bruce barker
    Jan 31, 2007
  4. james_027

    class attributes & data attributes

    james_027, Jun 20, 2007, in forum: Python
    Replies:
    2
    Views:
    385
    Bruno Desthuilliers
    Jun 20, 2007
  5. Kyle Schmitt
    Replies:
    3
    Views:
    202
    Kyle Schmitt
    Jul 24, 2007
Loading...

Share This Page