Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Techniques for reducing database queries in a Rails app

If you have a Rail app with many complex associated models, what techniques do you employ to reduce database queries?

In fact, I'll extend that question a little further and ask, what do you consider "too many" queries for any page?

I have a page that I expect will end up hitting the database about 20 times each page load. That concerns be but don't know whether it should concern me, or what I can do to reduce the load?

like image 324
aaronrussell Avatar asked Jan 28 '10 12:01

aaronrussell


2 Answers

Check out: bullet

Its a great way to identify n+1 queries and it offers suggestions to minimize it.

It does slow down development mode, so be sure to disable it when you are not performance tuning.

While we are at it, also checkout: rails_indexes

A simple way to identify which indexes your app could be missing.

Happy tuning.

like image 69
Jonathan Avatar answered Oct 14 '22 01:10

Jonathan


One common practice is judicious use of the include => :association option.

For instance on a controller you might do:

def show
    @items = Item.find(:all) 
end

...and the show view would do something like:

<% @items.each |item| %>
    <%= item.product.title %>
<% end %>

This will create a query for every call to product. But if you declare the association included as follows, you get eagerly-loaded associations in one query:

def show
    @items = Item.find(:all, :include => :product)
end

As always, check your console for query times and such.

like image 39
Dave Sims Avatar answered Oct 14 '22 00:10

Dave Sims