Skip to content

Commit

Permalink
Allow one to set strict_loading_mode globally
Browse files Browse the repository at this point in the history
  • Loading branch information
gjtorikian committed Mar 17, 2024
1 parent b8a399c commit 3a0a713
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
8 changes: 7 additions & 1 deletion activerecord/lib/active_record/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,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

Expand Down Expand Up @@ -668,6 +669,11 @@ def strict_loading!(value = true, mode: :all)

attr_reader :strict_loading_mode

# Returns +true+ if the record uses strict_loading with +:all+ mode enabled.
def strict_loading_all?
@strict_loading_mode == :all
end

# Returns +true+ if the record uses strict_loading with +:n_plus_one_only+ mode enabled.
def strict_loading_n_plus_one_only?
@strict_loading_mode == :n_plus_one_only
Expand Down Expand Up @@ -770,7 +776,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
Expand Down
14 changes: 14 additions & 0 deletions activerecord/test/cases/strict_loading_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,20 @@ def test_strict_loading_n_plus_one_only_mode
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 d.strict_loading? }
Expand Down
4 changes: 4 additions & 0 deletions guides/source/configuring.md
Original file line number Diff line number Diff line change
Expand Up @@ -1146,6 +1146,10 @@ 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. Deaults to `:all`.

#### `config.active_record.warn_on_records_fetched_greater_than`

Allows setting a warning threshold for query result size. If the number of
Expand Down

0 comments on commit 3a0a713

Please sign in to comment.