instance method reset_counters

Ruby on Rails 4.1.16

Since v4.0.13

Available in: v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

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 association counters 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/counter_cache.rb, line 20
      def reset_counters(id, *counters)
        object = find(id)
        counters.each do |association|
          has_many_association = _reflect_on_association(association.to_sym)
          raise ArgumentError, "'#{self.name}' has no association called '#{association}'" unless has_many_association

          if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
            has_many_association = has_many_association.through_reflection
          end

          foreign_key  = has_many_association.foreign_key.to_s
          child_class  = has_many_association.klass
          reflection   = child_class._reflections.values.find { |e| :belongs_to == e.macro && e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
          counter_name = reflection.counter_cache_column

          stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
            arel_table[counter_name] => object.send(association).count(:all)
          }, primary_key)
          connection.update stmt
        end
        return true
      end

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

Defined in ActiveRecord::CounterCache::ClassMethods

Type at least 2 characters to search.

↑↓ navigate · open · esc close