Counter Cache in rails 2.1

December 10, 2008 at 7:00 am Leave a comment

Counter cache is really an important feature in rails 2.1 . This method is really helpful when u want to keep a count on something and avoid firing sql query every time which results in more processing times.

Here it goes

To activate this feature, you need to take two simple steps. First, add the
option :counter_cache to the belongs_to declaration in the child table.

class LineItem true
end

Second, in the definition of the parent table (products in this example) you
need to add an integer column whose name is the name of the child table with
_count appended.

create_table :products, :force => true do |t|
t.column :title, :string
t.column :description, :text
# …
t.column :line_items_count, :integer, :default => 0
end

Thats it .. Counter cache is enabled now.

Advertisement

Entry filed under: counter cache in rails. Tags: .

Memcached with nginx on rails Spam filtering in rails using Akismet

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 )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed



Follow

Get every new post delivered to your Inbox.