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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With