ruby-on-railsrubyhas-manybelongs-tocounter-cache

Starting a counter cache from greater than 0


I have records that has_many objects. The objects have already been created with the record_id column prepopulated with a future record.id in mind. However when that future record is created, the counter cache always starts at 0.

How can I make the counter cache start at the correct number of associated objects instead of zero?


Solution

  • You are probably looking for the reset_counters method. From the docs:

    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.

    Example:

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