aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorRyuta Kamizono <kamipo@gmail.com>2018-05-26 16:14:26 +0900
committerRyuta Kamizono <kamipo@gmail.com>2018-05-26 16:21:03 +0900
commitcbab69c2789ff49bd9e3580eba0ac273190c9dc7 (patch)
tree60ec92e3d3da7873b8a0d59f1ce40b4627f9af0b /activerecord
parent7ac5b9e8486b90e7a6003a1b5e34b0fd530e6683 (diff)
downloadrails-cbab69c2789ff49bd9e3580eba0ac273190c9dc7.tar.gz
rails-cbab69c2789ff49bd9e3580eba0ac273190c9dc7.tar.bz2
rails-cbab69c2789ff49bd9e3580eba0ac273190c9dc7.zip
Avoid a subquery in updating counter cache
Since UPDATE with a subquery doesn't work on MySQL.
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/associations/builder/belongs_to.rb7
-rw-r--r--activerecord/lib/active_record/counter_cache.rb8
2 files changed, 8 insertions, 7 deletions
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb
index 852a858d9b..1dd6e5bed8 100644
--- a/activerecord/lib/active_record/associations/builder/belongs_to.rb
+++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -63,12 +63,7 @@ module ActiveRecord::Associations::Builder # :nodoc:
private
def counter_cache_target(reflection, model, foreign_key)
primary_key = reflection.association_primary_key(model)
-
- if primary_key == model.primary_key
- foreign_key
- else
- model.unscoped.where!(primary_key => foreign_key)
- end
+ model.unscoped.where!(primary_key => foreign_key)
end
end
end
diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb
index ee4f818cbf..faaedf1d4a 100644
--- a/activerecord/lib/active_record/counter_cache.rb
+++ b/activerecord/lib/active_record/counter_cache.rb
@@ -111,7 +111,13 @@ module ActiveRecord
updates << sanitize_sql_for_assignment(touch_updates) unless touch_updates.empty?
end
- unscoped.where(primary_key => id).update_all updates.join(", ")
+ if id.is_a?(Relation) && self == id.klass
+ relation = id
+ else
+ relation = unscoped.where!(primary_key => id)
+ end
+
+ relation.update_all updates.join(", ")
end
# Increment a numeric field by one, via a direct SQL update.