5 Ways to set Attributes in ActiveRecord

Rails 3 allows the developer to change ActiveRecord attributes in various ways. Each one does it slightly differently with sometimes unique side-effects. It’s important you understand which method to use, so here’s a short list (and a neat cheat table at the end!)

user.name = “Rob”

This regular assignment is the most common and easiest to use. It is the default write accessor generated by Rails. The name attribute will be marked as dirty and the change will not be sent to the database yet.

You can undo the change by calling reload! or save the change to the database by calling save.

user.write_attribute(:name, “Rob”)

This is the method that is called by the default accessor above. A synonym for this function is user[:name] = “Rob”. It also has a read_attribute counterpart.

Just like above, this method does not yet change the attribute in the database. Use this method anywhere you need to bypass the default write accessor above, for example when you want to write a custom attribute= writer.

user.update_attribute(:name, “Rob”)

This method will change the attribute in the model and pass it straight to the database, without running any validations.

Two gotchas:

  • Any other changed attributes are also saved to the database.
  • Validations are skipped so you could end up with invalid data.

Because of that last quirk it’s a good practice to use update_attributes instead.

user.attributes = {:name => “Rob”}

This method will set all the attributes you pass it, except those who are protected from mass assignment if you’re using attr_protected or attr_accessible. The changes are not saved to the database.

You can override the mass assignment protection by passing false:

user.send(:attributes=, {:name => "Rob"}, false)

user.update_attributes(:name => “Rob”)

This method changes the attributes of the model, checks the validations, and updates the record in the database if it validates. Since it uses the above attributes= method, attributes protected from mass assignment are not changed.

Note that just like update_attribute this method also saves other changed attributes to the database.

Handy Cheat Sheet Table

Method Uses Default Accessor Mass Assignment Protection Saved to Database Validations
attribute= Yes No No n/a
write_attribute No No No n/a
update_attribute Yes No Yes No
attributes= Yes Yes1 No n/a
update_attributes Yes Yes Yes Yes

If you want to understand more about these methods I suggest you check out their source code. Each time it’s only a couple of lines and it will really broaden your understanding of how Rails works!

  1. Mass Assignment Protection for attributes= is overridable. []
This entry was posted in Ruby on Rails. Bookmark the permalink.

23 Responses to 5 Ways to set Attributes in ActiveRecord

  1. Excellent post. I want to thank you for this informative read, I really appreciate
    sharing this great post. Keep up your work. Thanks for this very useful info you
    have provided us.

  2. Martin Streicer says:

    Recent changes in Rails 3 altered the behavior of update_attribute to run validations. Use update_column to save to the database without validations.

  3. Eric says:

    Thanks for answering my question!!!

  4. dennis says:

    Enjoyed the post! Thanks for the tips!

  5. tom says:

    this is great!

  6. derek feng says:

    excellent post. very basic staff that needs to be understood.

  7. Nolan says:

    Dig it!

  8. Kama says:

    This is my first visit to your site. Today I have got a new site. I am really happy to be here. I am stay tuned here for your next blog…

  9. Laura says:

    I enjoyed your entries on Toxic Words – such great thoughts and a wonderful reminder to watch the words I use – to be positive and kind and use

    words to build up rather than tear down. :)

  10. Madge says:

    Your website is really cool and this is a great inspiring article.

  11. Mabel says:

    Thanks for your marvelous posting! I actually enjoyed reading it, you will be a great author.I will ensure that I bookmark your blog and will

    come back in the foreseeable future. I want to encourage that you continue your great job, have a nice weekend!

  12. The worth of these tips will make me always remember this post, thanks for sharing it.

  13. folgen hier says:

    This was such a well structured tutorial, very good insight into the application for getting these amazing results.

  14. david says:

    Enjoyed the post! Thanks for the tips!
    fundraising options on long island

  15. Lipozene says:

    I like the cut of your job :) or at least your thought process but sorry to say, I honestly think you would have fully sold me on the idea had you been able to back up your premis with a substantial bit more solid facts.

  16. smith carlay says:

    To set effective information in features is not that a big process. But there are certain techniques that you need to adhere to. The five methods that you have proven here is ideal but I totally suggest that there are other techniques too.
    Full Body Workout Routine

  17. Thanks you for the cheat sheet. That was very helpful and solved my rails problem.. Thanks mate!

  18. This was such a well organized guide, very excellent understanding into the program for getting these awesome outcomes.
    Adelaide

  19. mindfulness says:

    Very interesting! Really very nice blog you Mindfulness Meditation

  20. mindfulness says:

    Your website is really cool and this is a great inspiring article.Mindfulness Meditation

  21. Can I just say, this blog is what got me through the day today.
    Every time I read it, I just get more and more excited about whats next.
    Very refreshing blog and very refreshing ideas.
    Im glad that I came across this when I did.
    I love what youve got to say and the way you say it.

  22. Grateful to check out your website, I seem to be ahead to more excellent content and I believe we all really like to thank for so many excellent content, weblog to discuss with us

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">