increment_counter
![Wide documentation Importance_3](https://d2vfyqvduarcvs.cloudfront.net/images/importance_3.png?1349367920)
increment_counter(counter_name, id)
public
Increments the specified counter by one. So DiscussionBoard.increment_counter("post_count", discussion_board_id) would increment the "post_count" counter on the board responding to discussion_board_id. This is used for caching aggregate values, so that they don’t need to be computed every time. Especially important for looping over a collection where each element require a number of aggregate values. Like the DiscussionBoard that needs to list both the number of posts and comments.
![Default_avatar_30](https://www.gravatar.com/avatar/b850a6cd0c0f8993fa152645ca9a7fbd?size=30&default=http://apidock.com/images/default_avatar_30.png)
See also: ActiveRecord::Base#increment
This is a class-level method. For the instance-level equivalent see: ActiveRecord::Base#increment
item = Item.find(1) item.foo_count # => 0 Item.increment_counter(:foo_count, 1) item.foo_count # => 0 item.reload item.foo_count # => 1 item.increment(:foo_count) item.foo_count # => 2
![Default_avatar_30](https://www.gravatar.com/avatar/009994c3985985809d2d644bd49aa1c2?size=30&default=http://apidock.com/images/default_avatar_30.png)
won't refresh updated_at
This will not cause :updated_at column to refresh, while ActiveRecord::Base#increment! would.
![Default_avatar_30](https://www.gravatar.com/avatar/77fd709e2756583da490164e9445958a?size=30&default=http://apidock.com/images/default_avatar_30.png)
The "instance-level equivalent" ActiveRecord::Base#increment is NOT atomic
Typically, you want to increment counters atomically, so the class method ActiveRecord::Base.increment_counter is the right choice.
Also, there is an issue with the increment example below as it does not save automatically:
item = Item.find(1) item.foo_count # => 0 item.increment(:foo_count) item.foo_count # => 1 item.reload item.foo_count # => 0 item.increment(:foo_count) item.save item.reload item.foo_count # => 1