class method self.reset_counters

Ruby on Rails 2.3.18

Since v2.3.18 Last seen in v2.3.18

Signature

self.reset_counters(id, *counters)

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.

Parameters

  • id - The id of the object you wish to reset a counter on.

  • counters - One or more counter names to reset

Examples

# For Post with id #1 records reset the comments_count
Post.reset_counters(1, :comments)

Parameters

id req
counters rest
Source
# File activerecord/lib/active_record/base.rb, line 936
      def reset_counters(id, *counters)
        object = find(id)
        counters.each do |association|
          child_class = reflect_on_association(association.to_sym).klass
          belongs_name = self.name.demodulize.underscore.to_sym
          counter_name = child_class.reflect_on_association(belongs_name).counter_cache_column
          value = object.send(association).count

          connection.update(<<-CMD, "#{name} UPDATE")
            UPDATE #{quoted_table_name}
            SET #{connection.quote_column_name(counter_name)} = #{value}
            WHERE #{connection.quote_column_name(primary_key)} = #{quote_value(object.id)}
          CMD
        end
        return true
      end

Defined in activerecord/lib/active_record/base.rb line 936 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Base

Type at least 2 characters to search.

↑↓ navigate · open · esc close