Do your DB calls in the controller not your views

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the rails category.

Last Updated: 2024-04-13

I had a bunch of DB-query triggering methods in some view code:

<% if @product.related_products %>
  <%= render partial: 'related_products', locals: {products: @product.related_products}  %>
<% end %>

After an upgrade that required some optimization of the database to maintain speed, I found it tricky to locate where exactly all my DB queries were located, since they were spread out over the views. I realized through these pains that this was a bad practice.

Ultimately I refactored all these queries out to the controller, so that they were visible (and could be DB-optimized) in one place:

class ProductController
  def show
    @product = Product.find(safe_params)
    @related_product = @product.includes(stuff_to_avoid_n_plus_1_queries)