Skip to content

Commit

Permalink
Avoid a subquery in updating counter cache
Browse files Browse the repository at this point in the history
Since UPDATE with a subquery doesn't work on MySQL.
  • Loading branch information
kamipo committed May 26, 2018
1 parent 7ac5b9e commit cbab69c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,7 @@ def belongs_to_counter_cache_after_update(reflection)
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
Expand Down
8 changes: 7 additions & 1 deletion activerecord/lib/active_record/counter_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,13 @@ def update_counters(id, counters)
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.
Expand Down

0 comments on commit cbab69c

Please sign in to comment.