Skip to content
Open
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
6 changes: 5 additions & 1 deletion lib/mongoid-denormalize.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@ def self.add_hook_to_child(child_class, fields, options)
from = options[:from].to_s

child_class.send(options[:child_callback] || 'before_save') do
if send("#{from}_id_changed?")
any_field_changed = fields.select do |field|
send("#{field[:as]}_changed?")
end

if send("#{from}_id_changed?") || any_field_changed
fields.each do |field|
send("#{field[:as]}=", send(from)&.send(field[:name]))
end
Expand Down
30 changes: 28 additions & 2 deletions spec/mongoid/denormalize_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ class Child
end
end

context 'when updates children denormalized field' do
it 'updates childs denormalized fields' do
parent = Parent.create!(name: 'parent')
child = Child.create!(parent: parent)

child.update_attributes(parent_name: 'new_name')
expect(child.reload.parent_name).to eq('parent')
end
end

context 'when updates relation' do
it 'updates denormalized fields' do
parent = Parent.create!(name: 'parent')
Expand Down Expand Up @@ -193,13 +203,21 @@ class Child
)
end

it 'updates childs denormalized fields' do
it 'updates parent denormalized fields' do
parent = Parent.create!(name: 'parent')
child = Child.create!(parent: parent)

parent.update_attributes(name: 'new_name')
expect(child.reload.parent_name).to eq('new_name')
end

it 'updates child denormalized fields' do
parent = Parent.create!(name: 'parent')
child = Child.create!(parent: parent)

child.update_attributes(parent_name: 'new_name')
expect(child.reload.parent_name).to eq('parent')
end
end
end
end
Expand Down Expand Up @@ -240,7 +258,7 @@ class Child
end

context 'when child exists' do
it 'updates childs denormalized fields' do
it 'updates parent denormalized fields' do
parent = Parent.create!(name: 'parent')
child = Child.create!(parent: parent)

Expand All @@ -255,6 +273,14 @@ class Child
child.update_attributes(parent: nil)
expect(child.reload.parent_name).to eq(nil)
end

it 'updates child denormalized fields' do
parent = Parent.create!(name: 'parent')
child = Child.create!(parent: parent)

child.update_attributes(parent_name: 'new_name')
expect(child.reload.parent_name).to eq('parent')
end
end

context 'when child does not exist' do
Expand Down