Fix delete_all when chained with joins #5202

Closed
wants to merge 2 commits into
from
Jump to file or symbol
Failed to load files and symbols.
+26 −2
Split
@@ -408,7 +408,13 @@ def delete_all(conditions = nil)
if conditions
where(conditions).delete_all
else
- statement = arel.compile_delete
+ statement = if joins_values.present?
+ pk = "#{@klass.quoted_table_name}.#{@klass.quoted_primary_key}"
+ ids = select(pk)
+ unscoped { @klass.where("#{pk} IN (SELECT * FROM (#{ids.to_sql}) AS derived_#{table_name}_#{primary_key}_ids)").build_arel.compile_delete }
+ else
+ arel.compile_delete
+ end
affected = @klass.connection.delete(statement, 'SQL', bind_values)
reset
@@ -13,12 +13,14 @@
require 'models/parrot'
require 'models/minivan'
require 'models/person'
+require 'models/pet'
+require 'models/toy'
require 'rexml/document'
require 'active_support/core_ext/exception'
class PersistencesTest < ActiveRecord::TestCase
- fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts, :minivans
+ fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts, :minivans, :pets, :toys
# Oracle UPDATE does not support ORDER BY
unless current_adapter?(:OracleAdapter)
@@ -76,6 +78,22 @@ def test_delete_all
assert_equal Topic.count, Topic.delete_all
end
+ def test_delete_all_with_joins_and_where_part_is_hash
+ where_args = {:toys => {:name => 'Bone'}}
+ count = Pet.joins(:toys).where(where_args).count
+
+ assert_equal count, 1
+ assert_equal count, Pet.joins(:toys).where(where_args).delete_all
+ end
+
+ def test_delete_all_with_joins_and_where_part_is_not_hash
+ where_args = ['toys.name = ?', 'Bone']
+ count = Pet.joins(:toys).where(where_args).count
+
+ assert_equal count, 1
+ assert_equal count, Pet.joins(:toys).where(where_args).delete_all
+ end
+
def test_update_by_condition
Topic.update_all "content = 'bulk updated!'", ["approved = ?", true]
assert_equal "Have a nice day", Topic.find(1).content