Allow one to set strict_loading_mode globally

This commit is contained in:
Garen J. Torikian 2024-03-17 12:38:38 -04:00
parent 8336aa7f0b
commit 5ff9915db9
No known key found for this signature in database
4 changed files with 28 additions and 1 deletions

@ -1,3 +1,9 @@
* Allow to configure `strict_loading_mode` globally or within a model.
Defaults to `:all`, can be changed to `:n_plus_one_only`.
*Garen Torikian*
* Add `ActiveRecord::Relation#readonly?`.
Reflects if the relation has been marked as readonly.

@ -89,6 +89,7 @@ def self.configurations
class_attribute :belongs_to_required_by_default, instance_accessor: false
class_attribute :strict_loading_by_default, instance_accessor: false, default: false
class_attribute :strict_loading_mode, instance_accessor: false, default: :all
class_attribute :has_many_inversing, instance_accessor: false, default: false
@ -784,7 +785,7 @@ def init_internals
@primary_key = klass.primary_key
@strict_loading = klass.strict_loading_by_default
@strict_loading_mode = :all
@strict_loading_mode = klass.strict_loading_mode
klass.define_attribute_methods
end

@ -98,6 +98,20 @@ def test_strict_loading_n_plus_one_only_mode_does_not_eager_load_child_associati
end
end
def test_default_mode_is_all
developer = Developer.first
assert_predicate developer, :strict_loading_all?
end
def test_default_mode_can_be_changed_globally
developer = Class.new(ActiveRecord::Base) do
self.strict_loading_mode = :n_plus_one_only
self.table_name = "developers"
end.new
assert_predicate developer, :strict_loading_n_plus_one_only?
end
def test_strict_loading
Developer.all.each { |d| assert_not d.strict_loading? }
Developer.strict_loading.each { |d| assert_predicate d, :strict_loading? }

@ -1284,6 +1284,12 @@ changed to `:log` to send violations to the logger instead of raising.
Is a boolean value that either enables or disables strict_loading mode by
default. Defaults to `false`.
#### `config.active_record.strict_loading_mode`
Sets the mode in which strict loading is reported. Defaults to `:all`. It can be
changed to `:n_plus_one_only` to only report when loading associations that will
lead to an N + 1 query.
#### `config.active_record.warn_on_records_fetched_greater_than`
Allows setting a warning threshold for query result size. If the number of