Shiva Kumar 's Blog

Start small,Think Big

Counter_cache => true (improves performance )

Counter cache is a simple feature that keeps the count of child object in parent table .So that you dont have to perform a query to find the size of the object each time  .Rails automatically updates the counter when there is association made between the parent and child .Adding counter_cache to new table is dead simple.Add a column in parent table for the associated object you want to create counter cache .Naming convention is something like pluralize the object name followed by ‘_count’


In child model here i.e comment.rb simply add counter_cache => true

Thats it.You don’t have to perform sql query to find size of object all time .This gradually increases your performance..


What if u wanted to add a counter cache column to existing table..


reset_column_information – before adding its resets all the cached information about columns

Then find all the data in that table and iterate,update  the counter cached  column .update_counters is  primarily to be used by increment_counter and decrement_counter ,its accepts two parameters a id and array of hash .We update the counter cache column.


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">