Friday, December 16, 2011

Avoiding Rails's 'validates_uniqueness_of' hits the Database

Disclaimer: I am now working with Rails 3.0.X, so this can be solved in newer branches (or not).

Sometimes something that starts as an stupid doubt takes you to useful improvements.

This morning, I was wondering if ActiveRecord is smart enough to avoid hitting the Database with an Update, when you save an unchanged object. My intuition said that none UPDATE should be done if nothing really has changed. So, doing a 'save' is always safe.

I fired up the console and activated the SQL log (as described here ). It turned out that ActiveRecord is smart enought to avoid issuing an SQL UPDATE if object is unchanged.

However I noticed a SELECT access while saving. Mmmm ....... from nowehere?

Well, it was certainly from somewhere:

 validates_uniqueness_of :username

This innocent line was fired on each validation, even if username didnt changed. The solition was really simple:

validates_uniqueness_of :username, :if => :username_changed?

The check is skipped when no really needed.
Profit!