1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Avoid extra scoping when using Relation#update

Since 9ac7dd4, class level `update`, `destroy`, and `delete` were placed
in the `Persistence` module as class methods.

But `Relation#update` without passing ids which was introduced at #11898
is not a class method, and it was caused the extra scoping regression
#33470.

I moved the relation method back into the `Relation` to fix the
regression.

Fixes #33470.
This commit is contained in:
Ryuta Kamizono 2018-07-31 08:17:45 +09:00
parent e8dd2bf857
commit c83e30da27
3 changed files with 9 additions and 3 deletions

View file

@ -107,13 +107,11 @@ module ActiveRecord
# When running callbacks is not needed for each record update,
# it is preferred to use {update_all}[rdoc-ref:Relation#update_all]
# for updating all records in a single query.
def update(id = :all, attributes)
def update(id, attributes)
if id.is_a?(Array)
id.map { |one_id| find(one_id) }.each_with_index { |object, idx|
object.update(attributes[idx])
}
elsif id == :all
all.each { |record| record.update(attributes) }
else
if ActiveRecord::Base === id
raise ArgumentError,

View file

@ -375,6 +375,10 @@ module ActiveRecord
@klass.connection.update stmt, "#{@klass} Update All"
end
def update(attributes) # :nodoc:
each { |record| record.update(attributes) }
end
def update_counters(counters) # :nodoc:
touch = counters.delete(:touch)

View file

@ -30,7 +30,9 @@ class RelationTest < ActiveRecord::TestCase
class TopicWithCallbacks < ActiveRecord::Base
self.table_name = :topics
cattr_accessor :topic_count
before_update { |topic| topic.author_name = "David" if topic.author_name.blank? }
after_update { |topic| topic.class.topic_count = topic.class.count }
end
def test_do_not_double_quote_string_id
@ -1576,6 +1578,8 @@ class RelationTest < ActiveRecord::TestCase
topics = TopicWithCallbacks.where(id: [topic1.id, topic2.id])
topics.update(title: "adequaterecord")
assert_equal TopicWithCallbacks.count, TopicWithCallbacks.topic_count
assert_equal "adequaterecord", topic1.reload.title
assert_equal "adequaterecord", topic2.reload.title
# Testing that the before_update callbacks have run