Rails reset counter caches
Today I learned that Rails has an easy way to reset counter caches
You just need to call reset_counters(id, *counters)
method
irb> Organization.reset_counters(4, :repositories)
Organization Load (0.3ms) SELECT "organizations".* FROM "organizations" WHERE "organizations"."id" = $1 LIMIT $2 [["id", 4], ["LIMIT", 1]]
(0.5ms) SELECT COUNT(*) FROM "repositories" WHERE "repositories"."organization_id" = $1 [["organization_id", 4]]
SQL (2.1ms) UPDATE "organizations" SET "repositories_count" = 6 WHERE "organizations"."id" = $1 [["id", 4]]
=> true
Tweet