Created
November 16, 2010 23:09
-
-
Save mpakes/702709 to your computer and use it in GitHub Desktop.
Populate a cached counter via a single SQL query.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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;" | |
ActiveRecord::Base.connection.execute(sql); | |
end | |
def self.down | |
remove_column :media, :followers_count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment