diff --git a/lib/mongoid/fields.rb b/lib/mongoid/fields.rb index 5a37bb2171..7a218255a8 100644 --- a/lib/mongoid/fields.rb +++ b/lib/mongoid/fields.rb @@ -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) diff --git a/lib/mongoid/touchable.rb b/lib/mongoid/touchable.rb index ded0a8f884..c1c93f825c 100644 --- a/lib/mongoid/touchable.rb +++ b/lib/mongoid/touchable.rb @@ -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? diff --git a/spec/mongoid/attributes_spec.rb b/spec/mongoid/attributes_spec.rb index f8f026d039..386b645f97 100644 --- a/spec/mongoid/attributes_spec.rb +++ b/spec/mongoid/attributes_spec.rb @@ -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 diff --git a/spec/mongoid/fields_spec.rb b/spec/mongoid/fields_spec.rb index aed458fd61..9e7485b97c 100644 --- a/spec/mongoid/fields_spec.rb +++ b/spec/mongoid/fields_spec.rb @@ -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