Today I Learned

A Zero One initiative

Strict loading with Rails

Rails implements a feature called strict loading. This feature can help catch potential N+1 queries.

Did you know there are a couple of ways to enable strict loading?

1. Per Record

Rails let’s you enable strict loading on specific records at runtime:

post = Post.first

post.strict_loading! # Enable strict loading
post.strict_loading? # Check if strict loading is enabled on this object
# => true

2. Per model

Rails let’s you enable strict loading on all models of a specific type:

class Post < ApplicationRecord
  self.strict_loading_by_default = true

  has_many :comments, dependent: :destroy
end

post = Post.first
post.strict_loading?
# => true

3. Enable per association basis

Rails let’s you define strict loading for specific (or pesky) relations on a model:

class Post < ApplicationRecord
  has_many :comments, dependent: :destroy, strict_loading: true
  has_many :likes,    dependent: :destroy, strict_loading: false
end

4. Application wide

Rails also let’s you enable strict loading all across the board when you’re brave enough for the nuclear option:

# config/environments/development.rb

Rails.application.configure do
# ...
  config.active_record.strict_loading_by_default = true
# ...
end

Now that you know your options, you can enable it based on your appetite/distaste for N+1 queries!

Looking for help? Each developer at Zero One has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.