Skip to content

Commit dd16a10

Browse files
committed
Merge pull request rails#15099 from eileencodes/refactor_delete_records_method
Refactor delete_records method
2 parents 522110a + 34db2b7 commit dd16a10

File tree

3 files changed

+20
-16
lines changed

3 files changed

+20
-16
lines changed

activerecord/lib/active_record/associations/collection_association.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ def delete_all(dependent = nil)
194194
options[:dependent]
195195
end
196196

197-
delete_records(:all, dependent).tap do
197+
delete_or_nullify_all_records(dependent).tap do
198198
reset
199199
loaded!
200200
end

activerecord/lib/active_record/associations/has_many_association.rb

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -105,23 +105,27 @@ def inverse_updates_counter_cache?(reflection = reflection())
105105
}
106106
end
107107

108+
def delete_count(method, scope)
109+
if method == :delete_all
110+
scope.delete_all
111+
else
112+
scope.update_all(reflection.foreign_key => nil)
113+
end
114+
end
115+
116+
def delete_or_nullify_all_records(method)
117+
count = delete_count(method, self.scope)
118+
update_counter(-count)
119+
end
120+
108121
# Deletes the records according to the <tt>:dependent</tt> option.
109122
def delete_records(records, method)
110123
if method == :destroy
111124
records.each(&:destroy!)
112125
update_counter(-records.length) unless inverse_updates_counter_cache?
113126
else
114-
if records == :all || !reflection.klass.primary_key
115-
scope = self.scope
116-
else
117-
scope = self.scope.where(reflection.klass.primary_key => records)
118-
end
119-
120-
if method == :delete_all
121-
update_counter(-scope.delete_all)
122-
else
123-
update_counter(-scope.update_all(reflection.foreign_key => nil))
124-
end
127+
scope = self.scope.where(reflection.klass.primary_key => records)
128+
update_counter(-delete_count(method, scope))
125129
end
126130
end
127131

activerecord/lib/active_record/associations/has_many_through_association.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,13 +130,13 @@ def update_through_counter?(method)
130130
end
131131
end
132132

133+
def delete_or_nullify_all_records(method)
134+
delete_records(load_target, method)
135+
end
136+
133137
def delete_records(records, method)
134138
ensure_not_nested
135139

136-
# This is unoptimised; it will load all the target records
137-
# even when we just want to delete everything.
138-
records = load_target if records == :all
139-
140140
scope = through_association.scope
141141
scope.where! construct_join_attributes(*records)
142142

0 commit comments

Comments
 (0)