From b20949a133619a079382c1eaa5bdb576623bdd63 Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Wed, 29 Jan 2025 13:10:51 +0100 Subject: [PATCH] MONGOID-5825 Do not update timestamp on destroyed (#5939) (#5945) --- lib/mongoid/timestamps/created.rb | 9 ++++++++- spec/mongoid/timestamps/created_spec.rb | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/mongoid/timestamps/created.rb b/lib/mongoid/timestamps/created.rb index f0983c6764..6e2f817b69 100644 --- a/lib/mongoid/timestamps/created.rb +++ b/lib/mongoid/timestamps/created.rb @@ -22,13 +22,20 @@ module Created # @example Set the created at time. # person.set_created_at def set_created_at - if !timeless? && !created_at + if able_to_set_created_at? time = Time.configured.now self.updated_at = time if is_a?(Updated) && !updated_at_changed? self.created_at = time end clear_timeless_option end + + # Is the created timestamp able to be set? + # + # @return [ true, false ] If the timestamp can be set. + def able_to_set_created_at? + !frozen? && !timeless? && !created_at + end end end end diff --git a/spec/mongoid/timestamps/created_spec.rb b/spec/mongoid/timestamps/created_spec.rb index f2e56d1f6d..c41bdb5884 100644 --- a/spec/mongoid/timestamps/created_spec.rb +++ b/spec/mongoid/timestamps/created_spec.rb @@ -43,4 +43,27 @@ expect(quiz.created_at).to be_within(10).of(Time.now.utc) end end + + context "when the document is destroyed" do + let(:book) do + Book.create! + end + + before do + Cover.before_save do + destroy if title == "delete me" + end + end + + after do + Cover.reset_callbacks(:save) + end + + it "does not set the created_at timestamp" do + book.covers << Cover.new(title: "delete me") + expect { + book.save + }.not_to raise_error + end + end end