From 9912e9c594a9732dcab783f812d68e80b37d4b1f Mon Sep 17 00:00:00 2001 From: Bruno Vezoli Date: Tue, 25 May 2021 11:40:52 -0300 Subject: [PATCH] Fix error message on top level update when sending an array of records --- activerecord/lib/active_record/persistence.rb | 5 +++++ activerecord/test/cases/persistence_test.rb | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index a0332cce5e..578d78497e 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -308,6 +308,11 @@ module ActiveRecord # for updating all records in a single query. def update(id = :all, attributes) if id.is_a?(Array) + if id.any?(ActiveRecord::Base) + raise ArgumentError, + "You are passing an array of ActiveRecord::Base instances to `update`. " \ + "Please pass the ids of the objects by calling `pluck(:id)` or `map(&:id)`." + end id.map { |one_id| find(one_id) }.each_with_index { |object, idx| object.update(attributes[idx]) } diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb index 524424c820..4b87ac2f21 100644 --- a/activerecord/test/cases/persistence_test.rb +++ b/activerecord/test/cases/persistence_test.rb @@ -64,6 +64,18 @@ class PersistenceTest < ActiveRecord::TestCase assert_not_equal "1 updated", Topic.first.content end + def test_update_many_with_array_of_active_record_base_objects + error = assert_raise(ArgumentError) do + Topic.update(Topic.first(2), content: "updated") + end + + assert_equal "You are passing an array of ActiveRecord::Base instances to `update`. " \ + "Please pass the ids of the objects by calling `pluck(:id)` or `map(&:id)`.", error.message + + assert_not_equal "updated", Topic.first.content + assert_not_equal "updated", Topic.second + end + def test_class_level_update_without_ids topics = Topic.all assert_equal 5, topics.length