Gem of the Week: Bullet
Optimizing Database Queries in Rails With Eager Loading and Bullet

bullet

A problem I’ve run into before when creating reporting or searching/filtering functionality (or potentially any feature in any project) is making sure I have my eager loading on point. Despite best efforts, something always slips through at some point, which can impact the performance of your app.

Enter Bullet. A neat little gem that very quickly (and easily) enables you to find any situations where eager loading should be used but is currently not. It can also integrate with many other systems out of the box such as rollbar or airbrake with a single line of configuration.

To get started, add the gem to your Gemfile, probably only in your development environment:

gem "bullet", :group => "development"

Then add the following to your config/environments/development.rb file


config.after_initialize do
  Bullet.enable = true
  Bullet.alert = true
end

This activates bullet and will enable Javascript alerts in your browser when a page is loaded that is found to have an N+1 query that could benefit from eager loading, showing you the exact line of the missing eager load:

eager

This is the easiest way to get started, and you can check out the Readme to see some other configuration options that might work best with your application.

A few lines of code highlights opportunities for enormous improvements in database query performance, which only take a few lines of code to implement.  It really cannot get any easier than this.