Skip to content

Commit

Permalink
Merge pull request rails#42290 from brunvez/top_level_update_error_me…
Browse files Browse the repository at this point in the history
…ssage

Fix error message on top level update when sending an array of records
  • Loading branch information
eugeneius authored May 27, 2021
2 parents fdce2a2 + 9912e9c commit df76f07
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
5 changes: 5 additions & 0 deletions activerecord/lib/active_record/persistence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,11 @@ def instantiate(attributes, column_types = {}, &block)
# 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])
}
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/persistence_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,18 @@ def test_update_many_with_active_record_base_object
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
Expand Down

0 comments on commit df76f07

Please sign in to comment.