Updating Objects

Many times, you have an object, and you want to only update a piece of data. While you could use @var.save, that would save the entire model instance, not just a piece.

Say you have a news website that runs a list of articles. You track the number of views. When viewed, you want to increment the number of views.

What do you do? In the show page, you could do this:


@article.views += 1
@article.save

While this works, the problem is that it re-saves the ENTIRE article, NOT just the number of views. If you get thousands of views per hour, this could prove to be a scalability bottleneck! So what do you do?

The answer is that you use update instead of save. Update takes two parameters–the ID of the row/instance to update, and a hash of which values to update. Use this code instead of the above:

Article.update(@article.id, {:views => @article.views + 1}

And that’s it! Rails will increment the view-count without re-saving the entire article! Handy, eh?

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Comments are closed.