Created
January 21, 2009 22:58
-
-
Save mtodd/50327 to your computer and use it in GitHub Desktop.
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
class InvalidateCachedUnreadPostsCountsAndGenerateAllToSpeedUpLoad < ActiveRecord::Migration | |
def self.up | |
DiscussionGroupUnreadPostsCount.delete_all | |
all_users = User.find(:all) | |
all_users.in_groups_of(100) do |users| | |
fork do | |
# reconnect because forking rapes the connection pool | |
ActiveRecord::Base.connection.reconnect! | |
users.each do |u| | |
if u # in_groups_of gives nils instead of truncating the array | |
start_time = Time.now | |
discussion_groups = u.discussion_groups # not every user is part of every discussion group | |
discussion_groups.each do |dg| | |
# creates a count cache for this DiscussionGroup/User pair | |
DiscussionGroupUnreadPostsCount.create(:discussion_group_id => dg.id, :user_id => u.id) | |
# after_create handles counting the number of unread posts for the pair | |
end | |
puts "Created caches for User:#{u.id.to_s} for #{discussion_groups.size.to_s} [%.5fms]" % ((Time.now - start_time) * 1000.0) | |
end | |
end | |
end | |
end | |
Process.waitall # wait for all processes to complete, could add error checking | |
# otherwise the migration will finish before the subprocesses | |
# odds are that our connection went away while waiting, so reconnect | |
ActiveRecord::Base.connection.reconnect! | |
# otherwise the schema won't be able to be updated when all the processes | |
# ends since it disconnected | |
end | |
def self.down | |
# nothing | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment