Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MONGOID-5789 database_field_name given nil or empty string should raise UnknownAttribute exception #5836

Merged
merged 6 commits into from
Jul 12, 2024
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
3 changes: 2 additions & 1 deletion lib/mongoid/fields.rb
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,8 @@ def traverse_association_tree(key, fields, associations, aliased_associations)
#
# @api private
def database_field_name(name, relations, aliased_fields, aliased_associations)
return nil unless name.present?
return "" unless name.present?

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

Expand Down
2 changes: 1 addition & 1 deletion lib/mongoid/touchable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def _gather_touch_updates(now, field = nil)
field = database_field_name(field)

write_attribute(:updated_at, now) if respond_to?("updated_at=")
write_attribute(field, now) if field
write_attribute(field, now) if field.present?

touches = _extract_touches_from_atomic_sets(field) || {}
touches.merge!(_parent._gather_touch_updates(now) || {}) if _touchable_parent?
Expand Down
16 changes: 16 additions & 0 deletions spec/mongoid/attributes_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,22 @@
end
end

context "when given nil" do

it "returns nil" do
expect(person[nil]).to be nil
end

end

context "when given an empty string" do

it "returns nil" do
expect(person[""]).to be nil
end

end

context "when the field was not explicitly defined" do

context "when excluding with only and the field was not excluded" do
Expand Down
4 changes: 2 additions & 2 deletions spec/mongoid/fields_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1871,12 +1871,12 @@ class DiscriminatorChild2 < DiscriminatorParent

context 'given nil' do
subject { Person.database_field_name(nil) }
it { is_expected.to eq nil }
it { is_expected.to eq '' }
end

context 'given an empty String' do
subject { Person.database_field_name('') }
it { is_expected.to eq nil }
it { is_expected.to eq '' }
end

context 'given a String' do
Expand Down
Loading