Skip to content

Commit d4377aa

Browse files
authored
Merge pull request rails#47787 from Shopify/pm/cpk-destroy
Accept list of composite primary keys in #destroy
2 parents 59189d4 + d8c4217 commit d4377aa

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

activerecord/lib/active_record/persistence.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -526,7 +526,13 @@ def composite_query_constraints_list # :nodoc:
526526
# todos = [1,2,3]
527527
# Todo.destroy(todos)
528528
def destroy(id)
529-
if id.is_a?(Array)
529+
multiple_ids = if composite_primary_key?
530+
id.is_a?(Array) && id.first.is_a?(Array)
531+
else
532+
id.is_a?(Array)
533+
end
534+
535+
if multiple_ids
530536
find(id).each(&:destroy)
531537
else
532538
find(id).destroy

activerecord/test/cases/persistence_test.rb

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525

2626
class PersistenceTest < ActiveRecord::TestCase
2727
fixtures :topics, :companies, :developers, :accounts, :minimalistics, :authors, :author_addresses,
28-
:posts, :minivans, :clothing_items
28+
:posts, :minivans, :clothing_items, :cpk_books
2929

3030
def test_update_many
3131
topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
@@ -292,6 +292,40 @@ def test_destroy_many_with_invalid_id
292292
assert_equal clients, Client.find([2, 3])
293293
end
294294

295+
def test_destroy_with_single_composite_primary_key
296+
book = cpk_books(:cpk_great_author_first_book)
297+
298+
assert_difference("Cpk::Book.count", -1) do
299+
destroyed = Cpk::Book.destroy(book.id)
300+
assert_equal destroyed, book
301+
end
302+
end
303+
304+
def test_destroy_with_multiple_composite_primary_keys
305+
books = [
306+
cpk_books(:cpk_great_author_first_book),
307+
cpk_books(:cpk_great_author_second_book),
308+
]
309+
310+
assert_difference("Cpk::Book.count", -2) do
311+
destroyed = Cpk::Book.destroy(books.map(&:id))
312+
assert_equal books.sort, destroyed.sort
313+
assert destroyed.all?(&:frozen?), "destroyed clients should be frozen"
314+
end
315+
end
316+
317+
def test_destroy_with_invalid_ids_for_a_model_that_expects_composite_keys
318+
books = [
319+
cpk_books(:cpk_great_author_first_book),
320+
cpk_books(:cpk_great_author_second_book),
321+
]
322+
323+
assert_raise(ActiveRecord::RecordNotFound) do
324+
ids = books.map { |book| book.id.first }
325+
Cpk::Book.destroy(ids)
326+
end
327+
end
328+
295329
def test_becomes
296330
assert_kind_of Reply, topics(:first).becomes(Reply)
297331
assert_equal "The First Topic", topics(:first).becomes(Reply).title

0 commit comments

Comments
 (0)