Increment a number field by one, usually representing a count.
This is used for caching aggregate values, so that they don’t need to be computed every time. For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is shown it would have to run an SQL query to find how many posts and comments there are.
# Increment the post_count column for the record with an id of 5 DiscussionBoard.increment_counter(:post_count, 5)
# File activerecord/lib/active_record/base.rb, line 789 def increment_counter(counter_name, id) update_counters(id, counter_name => 1) end
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