Read more

Rails: Your index actions probably want strict_loading

Henning Koch
April 14, 2023Software engineer at makandra GmbH

By activating strict_loading Show archive.org snapshot you force developers to address n+1 queries Show archive.org snapshot by preloading all associations used in the index view. Using an association that is not preloaded will raise an ActiveRecord::StrictLoadingViolationError.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

I think it's a good default to activate strict_loading in your controllers' #index actions. This way, when a change introduces an n+1 query, your test suite will blow up.

Example

A typical #index action looks like this.

class CardsController < ApplicationController

  def index
    @cards = Card
      .where(...)
      .preload(:user, :deck)
      .to_a
  end

end

You can include strict_loading somewhere in the scope chain:

class CardsController < ApplicationController

  def index
    @cards = Card
      .where(...)
      .strict_loading
      .preload(:user, :deck)
      .to_a
  end

end

You can also use strict_loading!(mode: :n_plus_one_only) if you care only about has_many associations.

Alternatives

Use a gem like bullet Show archive.org snapshot to detect n+1 queries.

Posted by Henning Koch to makandra dev (2023-04-14 15:07)