Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/mongoid/fields.rb
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,13 @@ def database_field_name(name, relations, aliased_fields, aliased_associations)
return '' unless name.present?

key = name.to_s

# A key without a "." refers to an immediate field, so it resolves to
# its alias (or itself) with no splitting. Short-circuiting here avoids
# the split and dup on every read, which is a hot path. This mirrors the
# same optimization already applied to the matcher.
return aliased_fields[key]&.dup || key unless key.include?('.')

segment, remaining = key.split('.', 2)

# Don't get the alias for the field when a belongs_to association
Expand Down
8 changes: 8 additions & 0 deletions spec/mongoid/fields_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1814,6 +1814,14 @@ class DiscriminatorChild2 < DiscriminatorParent
it { is_expected.to eq '' }
end

context 'when the returned name is mutated' do
it 'does not corrupt the aliased field map' do
Person.database_field_name('test') << '_mutated'

expect(Person.database_field_name('test')).to eq('t')
end
end

context 'given a String' do
subject { Person.database_field_name(key.to_s) }

Expand Down
Loading