What is the best way to optimize slow ActiveRecord queries in a Rails application?

My Rails application is taking too long to get data from the database. How can I make those database queries faster?

If you are experiencing slow performance then there are some common pitfalls, like the notorious “N+1” problem when showing a list of things. What this means is that there is 1 overall query to bring back a collection of items, and then N more queries that are pulling individual values, with N additional separate queries happening in order to get detail for each object you’re displaying.

If you take a look at the terminal window while your app is loading a slow page, do you see a long list of repetitive SQL queries happening?

If not then knowing more about the overall architecture of your app will be quite helpful to figure out what is causing things to be slow.