Wednesday, November 10, 2010

ActiveRecord::Base increment & decrement method

Hi all,

Yesterday while i was working in a task, i need to increase the points of an user. For that i have used the update_attribute method like below

user = User.last
user.update_attribute(:points, 5)

Then i found the active record base in-built method called "increment" and "decrement". So i used the following method to increment/decrement the user points.

user.increment(:points) # it will increase points by 1(default increment count) and returns the user object(self)
user.save
user.increment!(:points) # and this one will do the above two operations i.e., assigns the value to the attribute and saves the record. It will returns true or false(validation result).

user.increment(:points, 5) # we can pass the value like this to increment the attribute by this much. Here points will increases by 5
user.save
user.increment!(:points, 5)

The same is applicable to the "decrement" method, syntax is given below
user.decrement(:points)
user.decrement!(:points)
user.decrement(:points, 5)
user.decrement!(:points, 5)


Thanks,
Vadivelan