Permalink
Browse files

Merge pull request #15099 from eileencodes/refactor_delete_records_me…

…thod

Refactor delete_records method
  • Loading branch information...
2 parents 522110a + 34db2b7 commit dd16a1029ac34c09ce66fe7b088431bba920c1ba @tenderlove tenderlove committed May 14, 2014
@@ -194,7 +194,7 @@ def delete_all(dependent = nil)
options[:dependent]
end
- delete_records(:all, dependent).tap do
+ delete_or_nullify_all_records(dependent).tap do
reset
loaded!
end
@@ -105,23 +105,27 @@ def inverse_updates_counter_cache?(reflection = reflection())
}
end
+ def delete_count(method, scope)
+ if method == :delete_all
+ scope.delete_all
+ else
+ scope.update_all(reflection.foreign_key => nil)
+ end
+ end
+
+ def delete_or_nullify_all_records(method)
+ count = delete_count(method, self.scope)
+ update_counter(-count)
+ end
+
# Deletes the records according to the <tt>:dependent</tt> option.
def delete_records(records, method)
if method == :destroy
records.each(&:destroy!)
update_counter(-records.length) unless inverse_updates_counter_cache?
else
- if records == :all || !reflection.klass.primary_key
- scope = self.scope
- else
- scope = self.scope.where(reflection.klass.primary_key => records)
- end
-
- if method == :delete_all
- update_counter(-scope.delete_all)
- else
- update_counter(-scope.update_all(reflection.foreign_key => nil))
- end
+ scope = self.scope.where(reflection.klass.primary_key => records)
+ update_counter(-delete_count(method, scope))
end
end
@@ -130,13 +130,13 @@ def update_through_counter?(method)
end
end
+ def delete_or_nullify_all_records(method)
+ delete_records(load_target, method)
+ end
+
def delete_records(records, method)
ensure_not_nested
- # This is unoptimised; it will load all the target records
- # even when we just want to delete everything.
- records = load_target if records == :all
-
scope = through_association.scope
scope.where! construct_join_attributes(*records)

0 comments on commit dd16a10

Please sign in to comment.