Rails 2.1: Increment and Decrement Value

Rails allows you to easily increment and decrement fields on your ActiveRecord objects, like so:


page.increment!(:num_views)

ad.decrement!(:views_left)

But what if you want to increment or decrement by more than one? Prior to Rails 2.1, you needed to do this manually:


comment.increment!(:spam_score)
comment.increment!(:spam_score)
comment.increment!(:spam_score)

… would increment by three. In Rails 2.1, increment and decrement both take a second (optional) value of how much to increment or decrement by:


comment.increment!(:spam_score, 3)

And yes, you can pass in negative values (though why would you, if you have both increment and decrement functions?)

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.