Skip to content

Commit

Permalink
MONGOID-4578 allow setting a nested value to a non-string (#4510)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdehoog authored and saghm committed Sep 13, 2018
1 parent 394145b commit 48673d7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
10 changes: 5 additions & 5 deletions lib/mongoid/persistable/settable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ def set(setters)

field_and_value_hash = hasherizer(field.split('.'), value)
field = field_and_value_hash.keys.first.to_s
value = field_and_value_hash[field]

if fields[field] && fields[field].type == Hash && attributes.key?(field) && !value.empty?
if fields[field] && fields[field].type == Hash && attributes.key?(field) && Hash === value && !value.empty?
merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
value = (attributes[field] || {}).merge(field_and_value_hash[field], &merger)
process_attribute(field.to_s, value)
else
process_attribute(field.to_s, field_and_value_hash[field])
value = (attributes[field] || {}).merge(value, &merger)
end

process_attribute(field.to_s, value)

unless relations.include?(field.to_s)
ops[atomic_attribute_name(field)] = attributes[field]
end
Expand Down
19 changes: 19 additions & 0 deletions spec/mongoid/persistable/settable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,25 @@
end
end

context 'when a leaf value in the nested hash is updated to a number' do

let(:church) do
Church.new.tap do |a|
a.location = {'address' => {'city' => 'Berlin', 'street' => 'Yorckstr'}}
a.name = 'Church1'
a.save
end
end

before do
church.set('location.address.city' => 12345)
end

it 'updates the nested value to the correct value' do
expect(church.name).to eq('Church1')
expect(church.location).to eql({'address' => {'city' => 12345, 'street' => 'Yorckstr'}})
end
end

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

Expand Down

0 comments on commit 48673d7

Please sign in to comment.