Skip to content

Commit 06beda9

Browse files
authored
MONGOID-3601 Don't mark embedded objects as persisted when the parent is invalid (#5297)
* MONGOID-3601 what happens if we return nil on valdiation error? * MONGOID-3061 Don't mark embedded objects get marked as persisted even when the parent is invalid * clean up * MONGOID-3601 check for errors instead of persisted * MONGOID-3061 add document check
1 parent 7ce3f07 commit 06beda9

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

lib/mongoid/persistable/creatable.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,10 @@ def prepare_insert(options = {})
108108
_mongoid_run_child_callbacks(:save) do
109109
_mongoid_run_child_callbacks(:create) do
110110
result = yield(self)
111-
post_process_insert
112-
post_process_persist(result, options)
111+
if !result.is_a?(Document) || result.errors.empty?
112+
post_process_insert
113+
post_process_persist(result, options)
114+
end
113115
end
114116
end
115117
end

spec/mongoid/association/embedded/embeds_many/proxy_spec.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4719,4 +4719,25 @@ class DNS::Record
47194719
expect(post.company_tags.first.title).to eq("c")
47204720
end
47214721
end
4722+
4723+
context "when the parent fails validation" do
4724+
let(:school) { EmmSchool.new }
4725+
let(:student) { school.students.new }
4726+
4727+
before do
4728+
student.save
4729+
end
4730+
4731+
it "does not mark the parent as persisted" do
4732+
expect(school.persisted?).to be false
4733+
end
4734+
4735+
it "does not mark the child as persisted" do
4736+
expect(student.persisted?).to be false
4737+
end
4738+
4739+
it "does not persist the parent" do
4740+
expect(School.count).to eq(0)
4741+
end
4742+
end
47224743
end

spec/mongoid/association/embedded/embeds_many_models.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,3 +188,18 @@ class EmmUserTag
188188
embedded_in :post, class_name: "EmmPost"
189189
end
190190

191+
class EmmSchool
192+
include Mongoid::Document
193+
194+
embeds_many :students, class_name: "EmmStudent"
195+
196+
field :name, type: :string
197+
198+
validates :name, presence: true
199+
end
200+
201+
class EmmStudent
202+
include Mongoid::Document
203+
204+
embedded_in :school, class_name: "EmmSchool"
205+
end

0 commit comments

Comments
 (0)