Skip to content

Commit

Permalink
Prevent child double push when after_create callbacks save again. [ fix
Browse files Browse the repository at this point in the history
… #2331 ]
  • Loading branch information
durran committed Sep 16, 2012
1 parent da254d8 commit 2e140ef
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Expand Up @@ -110,6 +110,9 @@ For instructions on upgrading to newer versions, visit

### Resolved Issues

* \#2331 Don't double push child documents when extra saves are called in an
after_create callback.

## 3.0.6

### Resolved Issues
Expand Down
14 changes: 14 additions & 0 deletions lib/mongoid/hierarchy.rb
Expand Up @@ -44,6 +44,20 @@ def collect_children
children
end

# Marks all children as being persisted.
#
# @example Flag all the children.
# document.flag_children_persisted
#
# @return [ Array<Document> ] The flagged children.
#
# @since 3.0.7
def flag_children_persisted
_children.each do |child|
child.new_record = false
end
end

# Determines if the document is a subclass of another document.
#
# @example Check if the document is a subclass
Expand Down
1 change: 1 addition & 0 deletions lib/mongoid/persistence/insertion.rb
Expand Up @@ -24,6 +24,7 @@ def prepare(&block)
document.run_callbacks(:create) do
yield(document)
document.new_record = false
document.flag_children_persisted
true
end
end
Expand Down
5 changes: 5 additions & 0 deletions spec/app/models/server.rb
@@ -1,8 +1,13 @@
class Server
include Mongoid::Document
field :name, type: String
field :after, type: Boolean, default: false
belongs_to :node
embeds_many :filesystems, validate: false
accepts_nested_attributes_for :filesystems
validates :name, presence: { allow_blank: false }

after_create do |server|
server.update_attribute(:after, !after)
end
end
22 changes: 22 additions & 0 deletions spec/mongoid/relations/embedded/many_spec.rb
Expand Up @@ -3677,4 +3677,26 @@ class TrackingIdValidationHistory
end
end
end

context "when saving at the parent level" do

let!(:server) do
Server.new(name: "staging")
end

let!(:filesystem) do
server.filesystems.build
end

context "when the parent has an after create callback" do

before do
server.save
end

it "does not push the embedded documents twice" do
server.reload.filesystems.count.should eq(1)
end
end
end
end

0 comments on commit 2e140ef

Please sign in to comment.