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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)