Good Starting Points for Optimizing Database Calls in Ruby on Rails?

Posted by viatropos on Stack Overflow See other posts from Stack Overflow or by viatropos
Published on 2010-06-12T10:29:39Z Indexed on 2010/06/12 10:32 UTC
Read the original article Hit count: 315

Filed under:
|
|

I have a menu in Rails which grabs a nested tree of Post models, each which have a Slug model associated via a polymorphic association (using the friendly_id gem for slugs and awesome_nested_set for the tree).

The database output in development looks like this (here's the full gist):

SQL (0.4ms)  SELECT COUNT(*) AS count_id FROM "posts" WHERE ("posts".parent_id = 39)
CACHE (0.0ms)  SELECT "posts".* FROM "posts" WHERE ("posts"."id" = 13) LIMIT 1
CACHE (0.0ms)  SELECT "slugs".* FROM "slugs" WHERE ("slugs".sluggable_id = 13 AND "slugs".sluggable_type = 'Post') ORDER BY id DESC LIMIT 1
Slug Load (0.4ms)  SELECT "slugs".* FROM "slugs" WHERE ("slugs".sluggable_id = 40 AND "slugs".sluggable_type = 'Post') ORDER BY id DESC LIMIT 1
SQL (0.3ms)  SELECT COUNT(*) AS count_id FROM "posts" WHERE ("posts".parent_id = 40)
CACHE (0.0ms)  SELECT "posts".* FROM "posts" WHERE ("posts"."id" = 13) LIMIT 1
CACHE (0.0ms)  SELECT "slugs".* FROM "slugs" WHERE ("slugs".sluggable_id = 13 AND "slugs".sluggable_type = 'Post') ORDER BY id DESC LIMIT 1
Slug Load (0.4ms)  SELECT "slugs".* FROM "slugs" WHERE ("slugs".sluggable_id = 41 AND "slugs".sluggable_type = 'Post') ORDER BY id DESC LIMIT 1
...
Rendered shared/_menu.html.haml (907.6ms)

What are some quick things I should always do to optimize this from the start (easy things)?

Some things I'm thinking now are:

  • Can Rails 3 eager load the whole Post tree + associated Slugs in one DB call? Can I do that easily with named scopes or custom SQL?
  • What is best practice in this situation?

Not really thinking about memcached in this situation as that can be applied to much more than just this.

© Stack Overflow or respective owner

Related posts about sql

Related posts about ruby-on-rails