Skip to content

Commit

Permalink
Many to many #clear no longer deletes documents:
Browse files Browse the repository at this point in the history
- This simply nullifies the relation to be consistent with AR behaviour.
- For previous behaviour of #clear, please use #purge.
- Fixes #988.
  • Loading branch information
durran committed Aug 3, 2011
1 parent d09bc6a commit 12b42d8
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 24 deletions.
37 changes: 19 additions & 18 deletions lib/mongoid/relations/referenced/many.rb
Expand Up @@ -60,23 +60,6 @@ def build(attributes = {}, type = nil)
end
alias :new :build

# Clear the relation. Will delete the documents from the db if they are
# already persisted.
#
# @example Clear the relation.
# person.posts.clear
#
# @return [ Many ] The relation emptied.
#
# @since 2.0.0.beta.1
def clear
criteria.delete_all
target.clear do |doc|
unbind_one(doc)
doc.destroyed = true
end
end

# Creates a new document on the references many relation. This will
# save the document if the parent has been persisted.
#
Expand Down Expand Up @@ -259,6 +242,24 @@ def nullify
end
alias :nullify_all :nullify

# Clear the relation. Will delete the documents from the db if they are
# already persisted.
#
# @example Clear the relation.
# person.posts.clear
#
# @return [ Many ] The relation emptied.
#
# @since 2.0.0.beta.1
def purge
criteria.delete_all
target.clear do |doc|
unbind_one(doc)
doc.destroyed = true
end
end
alias :clear :purge

# Substitutes the supplied target documents for the existing documents
# in the relation. If the new target is nil, perform the necessary
# deletion.
Expand All @@ -273,7 +274,7 @@ def nullify
# @since 2.0.0.rc.1
def substitute(replacement)
tap do |proxy|
proxy.clear
proxy.purge
proxy.push(replacement) if replacement
end
end
Expand Down
11 changes: 8 additions & 3 deletions lib/mongoid/relations/referenced/many_to_many.rb
Expand Up @@ -171,14 +171,19 @@ def initialize(base, target, metadata)
#
# @since 2.0.0.rc.1
def nullify
# @todo: Durran: This is wrong.
criteria.update(metadata.inverse_foreign_key => [])
# We need to update the inverse as well.
criteria.pull(metadata.inverse_foreign_key, base.id)
unless base.destroyed?
base.set(
metadata.foreign_key,
base.send(metadata.foreign_key).clear
)
end
target.clear do |doc|
unbind_one(doc)
end
end
alias :nullify_all :nullify
alias :clear :nullify

private

Expand Down
Expand Up @@ -705,11 +705,11 @@
preference.person_ids.should_not include(person.id)
end

it "marks the documents as deleted" do
preference.should be_destroyed
it "does not delete the documents" do
preference.should_not be_destroyed
end

it "deletes the documents from the db" do
it "persists the nullification" do
person.reload.preferences.should be_empty
end

Expand Down

0 comments on commit 12b42d8

Please sign in to comment.