Skip to content

Commit

Permalink
Update migration to handle duplicate likes
Browse files Browse the repository at this point in the history
  • Loading branch information
Raphael Sofaer committed Jul 11, 2011
1 parent 67882c7 commit a7d8535
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions db/migrate/20110707234802_likes_on_comments.rb
@@ -1,4 +1,5 @@
class LikesOnComments < ActiveRecord::Migration
class Likes < ActiveRecord::Base; end
def self.up
remove_foreign_key :likes, :posts

Expand All @@ -11,7 +12,17 @@ def self.up
UPDATE likes
SET target_type = 'Post'
SQL
execute <<SQL
UPDATE posts
SET likes_count = (SELECT COUNT(*) FROM likes WHERE likes.target_id = posts.id AND likes.target_type = 'Post')
SQL

#There are some duplicate likes.
keeper_likes = Like.group(:target_id, :author_id, :target_type).having('COUNT(*) > 1')
keeper_likes.each do |like|
l = Like.arel_table
Like.where(:target_id => like.target_id, :author_id => like.author_id, :target_type => like.target_type).where(l[:id].not_eq(like.id)).delete_all
end
add_index :likes, [:target_id, :author_id, :target_type], :unique => true
end

Expand Down

0 comments on commit a7d8535

Please sign in to comment.