Rails: Your index actions probably want strict_loading

Updated . Posted . Visible to the public. Repeats.

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.

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.

Henning Koch
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2023-04-14 13:07)