instance method reset_counters

Ruby on Rails 3.0.20

Since v3.0.20 Last seen in v3.2.22.5

Available in: v3.0.20 v3.1.12 v3.2.22.5

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 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/counter_cache.rb, line 17
    def reset_counters(id, *counters)
      object = find(id)
      counters.each do |association|
        has_many_association = reflect_on_association(association.to_sym)

        expected_name = if has_many_association.options[:as]
          has_many_association.options[:as].to_s.classify
        else
          self.name
        end

        child_class  = has_many_association.klass
        belongs_to   = child_class.reflect_on_all_associations(:belongs_to)
        reflection   = belongs_to.find { |e| e.class_name == expected_name }
        counter_name = reflection.counter_cache_column

        self.unscoped.where(arel_table[self.primary_key].eq(object.id)).arel.update({
          arel_table[counter_name] => object.send(association).count
        })
      end
      return true
    end

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

Defined in ActiveRecord::CounterCache

Type at least 2 characters to search.

↑↓ navigate · open · esc close