Skip to content

Instantly share code, notes, and snippets.

View mpakes's full-sized avatar

Matt Pakes mpakes

View GitHub Profile

Keybase proof

I hereby claim:

  • I am mpakes on github.
  • I am mpakes (https://keybase.io/mpakes) on keybase.
  • I have a public key whose fingerprint is A4D5 4452 8979 CEA0 1CA9 A939 AAB9 0D9A C8E7 4C82

To claim this, I am signing this object:

@mpakes
mpakes / counter_backfill_migration.rb
Created November 16, 2010 23:09
Populate a cached counter via a single SQL query.
# Credit to Mike Perham for this gem of an idea
# http://www.mikeperham.com/2007/12/17/creating-a-counter_cache-column/
class RailsMigration < ActiveRecord::Migration
def self.up
add_column :media, :followers_count, :integer, :default => 0, :null => false
# Populate the media follower counter cache in one fell swoop.
sql = "update media, (select operable_id, count(*) as the_count from follow_operations "\
"group by operable_id) as follows set media.followers_count = follows.the_count "\
"where media.id = follows.operable_id;"