Rails Counter Cache


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.

Necessary steps.

  1. Add the counter_cache column as an integer.
  2. Make sure that the column is set to disallow null values and defaults to 0.
  3. 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.

Example:

class Organization < ActiveRecord::Base
    has_many :seasons
  end

  class Season < ActiveRecord::Base
    belongs_to :organization, :counter_cache => true
  end

That's it.

Cheers!!!


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s