Skip to content

Commit 6243dda

Browse files
alexandrebinisaghm
authored andcommitted
Fix cloning documents with deep embedded documents (#4504)
1 parent 8ee7ed9 commit 6243dda

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

lib/mongoid/copyable.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,9 @@ def process_localized_attributes(klass, attrs)
7373
next unless attrs.present? && attrs[association.key].present?
7474

7575
if association.is_a?(Association::Embedded::EmbedsMany)
76-
attrs[association.name.to_s].each_with_index do |attr, index|
77-
process_localized_attributes(send(association.name)[index].class, attr)
76+
attrs[association.name.to_s].each do |attr|
77+
embedded_klass = attr.fetch('_type', association.class_name).constantize
78+
process_localized_attributes(embedded_klass, attr)
7879
end
7980
else
8081
process_localized_attributes(association.klass, attrs[association.key])

spec/mongoid/copyable_spec.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@
3535
person.build_game(name: "Tron")
3636
end
3737

38+
let!(:name_translations) do
39+
person.name.translations.build(language: 'en')
40+
end
41+
3842
context "when the document has an id field in the database" do
3943

4044
let!(:band) do
@@ -245,14 +249,26 @@
245249
expect(copy.addresses).to eq(person.addresses)
246250
end
247251

252+
it "copys deep embeds many documents" do
253+
expect(copy.name.translations).to eq(person.name.translations)
254+
end
255+
248256
it "sets the embedded many documents as new" do
249257
expect(copy.addresses.first).to be_new_record
250258
end
251259

260+
it "sets the deep embedded many documents as new" do
261+
expect(copy.name.translations.first).to be_new_record
262+
end
263+
252264
it "creates new embeds many instances" do
253265
expect(copy.addresses).to_not equal(person.addresses)
254266
end
255267

268+
it "creates new deep embeds many instances" do
269+
expect(copy.name.translations).to_not equal(person.name.translations)
270+
end
271+
256272
it "copys embeds one documents" do
257273
expect(copy.name).to eq(person.name)
258274
end

0 commit comments

Comments
 (0)