Skip to content

Support strict_loading on association declarations#38541

Merged
eileencodes merged 1 commit intorails:masterfrom
kddnewton:strict-loading-associations
Feb 21, 2020
Merged

Support strict_loading on association declarations#38541
eileencodes merged 1 commit intorails:masterfrom
kddnewton:strict-loading-associations

Conversation

@kddnewton
Copy link
Copy Markdown
Contributor

Raise an error if attempting to load a record from an association that has been marked as strict_loading unless it was explicitly eager loaded.

class Developer < ApplicationRecord
  has_many :projects, strict_loading: true
end

dev = Developer.first
dev.projects.first
# => ActiveRecord::StrictLoadingViolationError: The projects association is marked as strict_loading and cannot be lazily loaded.

This is a follow up to the work done on #37400. It effectively allows you to declare that specific relations should always be treated as if the parent were marked in strict mode.

@eileencodes eileencodes merged commit 3dff30c into rails:master Feb 21, 2020
@eileencodes
Copy link
Copy Markdown
Member

Thanks Kevin!

@kddnewton kddnewton deleted the strict-loading-associations branch February 21, 2020 19:35
bogdanvlviv added a commit to bogdanvlviv/rails that referenced this pull request Jun 1, 2020
…:Base.strict_loading_by_default=`.

This will allow to enable/disable strict_loading mode by default for a model.
The configuration's value is inheritable by subclasses, but they can override that value and
it will not impact parent class:

```ruby
class Developer < ApplicationRecord
  self.strict_loading_by_default = true

  has_many :projects
end

dev = Developer.first
dev.projects.first
\# => ActiveRecord::StrictLoadingViolationError Exception: Developer is marked as strict_loading and Project cannot be lazily loaded.
```

What is great about this feature that it could help users to nip N+1 queries in
the bud, especially for fresh applications, by setting
`ActiveRecord::Base.strict_loading_by_default = true` / `config.active_record.strict_loading_by_default = true`.
That is also a great way to prevent new N+1 queries in the existing applications
after all the N+1 queries are eliminated.
(See https://guides.rubyonrails.org/v6.0/active_record_querying.html#eager-loading-associations,
https://github.com/seejohnrun/prelude for details on how to fight against N+1 queries).

Related to rails#37400, rails#38541
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants