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?)

Tags: ,     Posted in Development

Rate this article:
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Related Content


Leave a Reply