Module | ActiveRecord::CounterCache |
In: |
lib/active_record/counter_cache.rb
|
Decrement a number field by one, usually representing a count.
This works the same as increment_counter but reduces the column value by 1 instead of increasing it.
# Decrement the post_count column for the record with an id of 5 DiscussionBoard.decrement_counter(:post_count, 5)
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)
Resets one or more counter caches to their correct value using an SQL count query. This is useful when adding new counter caches, or if the counter has been corrupted or modified directly by SQL.
# For Post with id #1 records reset the comments_count Post.reset_counters(1, :comments)
A generic "counter updater" implementation, intended primarily to be used by increment_counter and decrement_counter, but which may also be useful on its own. It simply does a direct SQL update for the record with the given ID, altering the given hash of counters by the amount given by the corresponding value:
# For the Post with id of 5, decrement the comment_count by 1, and # increment the action_count by 1 Post.update_counters 5, :comment_count => -1, :action_count => 1 # Executes the following SQL: # UPDATE posts # SET comment_count = COALESCE(comment_count, 0) - 1, # action_count = COALESCE(action_count, 0) + 1 # WHERE id = 5 # For the Posts with id of 10 and 15, increment the comment_count by 1 Post.update_counters [10, 15], :comment_count => 1 # Executes the following SQL: # UPDATE posts # SET comment_count = COALESCE(comment_count, 0) + 1, # WHERE id IN (10, 15)