Rails: How to increment a counter without touching updated_at or serialized columns

When you have a table with serialized columns active record will always treat them as dirty. It can create unnecessary overhead when just incrementing a simple counter.

Fortunately rails has a method that just update the counter and nothing else.

apidock: update_counters

If you have a Movie model with a counter named like_count and you would like to increment it by one you would use the following method.

Movie.update_counters id, :like_count => 1

As a bonus you also get a locking

Posted in Programming, Rails at May 19th, 2012. Trackback URI: trackback Tags: , , Written by: 

It's past my bedtime is using WP-Gravatar