Counter Cache is a mechanism to cache the counts of associated model.Enabling counter cache will simply make Rails to increment and decrement the counter of associated objects. Whenever you need to execute size on ActiveRecord, Rails will use the cached counter.
- Add the counter_cache column as an integer.
- Make sure that the column is set to disallow null values and defaults to 0.
- Reset the counters for existing records. The reset_counters method is not smart enough to take an array of ids, so you have to call it for each record you want updated.
class Organization < ActiveRecord::Base has_many :seasons end class Season < ActiveRecord::Base belongs_to :organization, :counter_cache => true end That's it. Cheers!!!