Reset cache counter for all model data

I am looking for a great way to update the cache counter of this model.

Here is my model:

class GameParticipation < ActiveRecord::Base
  belongs_to :game, counter_cache: true
end

AND:

class Game < ActiveRecord::Base
  has_many   :game_participations
end

Isn't that better than repeating on every element, such as the following code?

Game.pluck(:id).map{|g_id| Game.reset_counters(g_id, :game_participations) }

(I use Rails4 and activerecord)

+4
source share
2 answers

To update the entire cache counter in one request, I found inspiration at http://ryan.mcgeary.org/2016/02/05/proper-counter-cache-migrations-in-rails/

This can be done in one query with SQL:

ActiveRecord::Base.connection.execute <<-SQL.squish
    UPDATE games
    SET game_participations_count = (SELECT count(1)
                               FROM game_participations
                              WHERE game_participations.game_id = games.id)
SQL

It takes much less time to complete, since all updates are performed in a single request.

+7
source

each, , , , . , ""?

0

All Articles