Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Feb 4 ’11

How to check if objects or relations exist

Here’s an interesting fact when checking if objects or relations exist in a collection.
To check if there were any items present in a collection you can do something like this:

Object.relation.present?

This, however, is better:

Object.relation.any?

Turns out that - when you request associated objects for the first time - 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.

blog = Blog.first
blog.posts.present?
# SQL (284.1ms)   SELECT * FROM "posts" WHERE ("posts".blog_id = 1)

blog = Blog.first
blog.posts.any?
# SQL (1.2ms)   SELECT count(*) AS count_all FROM "posts" WHERE ("posts".blog_id = 1)

Thanks to Mario and Keith for this tip.

39 notes 0 comments (via mariovisic)

  1. panp reblogged this from atm09td
  2. chuckjhardy reblogged this from rubyquicktips
  3. atm09td reblogged this from rubyquicktips
  4. rubyflare reblogged this from rubyquicktips
  5. rubyquicktips reblogged this from mariovisic and added:
    This, however, is better:...- when you request associated objects for the first time...
  6. mariovisic posted this

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus