Mario's Blog

The journal of a software developer who has a fondness of cheese

Checking if Objects or Relations Exist in Ruby on Rails

I was pair programming with the great magician Keith yesterday when he pointed out something interesting when checking if objects or relations exist in a collection.

To check if there were any items present in a collection I would do something like this:


Keith told me to use:


Turns out that the any? method will perform a COUNT (*) SQL query where as the present? method will perform a SELECT (*) which is infinitely slower than performing a count.

So from now on i’ll be using the any? method instead of present?