Skip to content

Instantly share code, notes, and snippets.

@mpakes
Created November 16, 2010 23:09
Show Gist options
  • Select an option

  • Save mpakes/702709 to your computer and use it in GitHub Desktop.

Select an option

Save mpakes/702709 to your computer and use it in GitHub Desktop.

Revisions

  1. mpakes revised this gist Nov 16, 2010. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions counter_backfill_migration.rb
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    # 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
  2. mpakes created this gist Nov 16, 2010.
    15 changes: 15 additions & 0 deletions counter_backfill_migration.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    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;"
    ActiveRecord::Base.connection.execute(sql);
    end

    def self.down
    remove_column :media, :followers_count
    end
    end