Skip to content

Commit 48673d7

Browse files
mdehoogsaghm
authored andcommitted
MONGOID-4578 allow setting a nested value to a non-string (#4510)
1 parent 394145b commit 48673d7

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

lib/mongoid/persistable/settable.rb

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,15 @@ def set(setters)
2525

2626
field_and_value_hash = hasherizer(field.split('.'), value)
2727
field = field_and_value_hash.keys.first.to_s
28+
value = field_and_value_hash[field]
2829

29-
if fields[field] && fields[field].type == Hash && attributes.key?(field) && !value.empty?
30+
if fields[field] && fields[field].type == Hash && attributes.key?(field) && Hash === value && !value.empty?
3031
merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
31-
value = (attributes[field] || {}).merge(field_and_value_hash[field], &merger)
32-
process_attribute(field.to_s, value)
33-
else
34-
process_attribute(field.to_s, field_and_value_hash[field])
32+
value = (attributes[field] || {}).merge(value, &merger)
3533
end
3634

35+
process_attribute(field.to_s, value)
36+
3737
unless relations.include?(field.to_s)
3838
ops[atomic_attribute_name(field)] = attributes[field]
3939
end

spec/mongoid/persistable/settable_spec.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,25 @@
315315
end
316316
end
317317

318+
context 'when a leaf value in the nested hash is updated to a number' do
319+
320+
let(:church) do
321+
Church.new.tap do |a|
322+
a.location = {'address' => {'city' => 'Berlin', 'street' => 'Yorckstr'}}
323+
a.name = 'Church1'
324+
a.save
325+
end
326+
end
327+
328+
before do
329+
church.set('location.address.city' => 12345)
330+
end
331+
332+
it 'updates the nested value to the correct value' do
333+
expect(church.name).to eq('Church1')
334+
expect(church.location).to eql({'address' => {'city' => 12345, 'street' => 'Yorckstr'}})
335+
end
336+
end
318337

319338
context 'when the nested hash is many levels deep' do
320339

0 commit comments

Comments
 (0)