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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)