20160603180330_remove_duplicated_notification_settings.rb 853 Bytes
Newer Older
1
class RemoveDuplicatedNotificationSettings < ActiveRecord::Migration[4.2]
2
  def up
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
    duplicates = exec_query(%Q{
      SELECT user_id, source_type, source_id
      FROM notification_settings
      GROUP BY user_id, source_type, source_id
      HAVING COUNT(*) > 1
    })

    duplicates.each do |row|
      uid = row['user_id']
      stype = connection.quote(row['source_type'])
      sid = row['source_id']

      execute(%Q{
        DELETE FROM notification_settings
        WHERE user_id = #{uid}
        AND source_type = #{stype}
        AND source_id = #{sid}
        AND id != (
          SELECT id FROM (
            SELECT min(id) AS id
            FROM notification_settings
            WHERE user_id = #{uid}
            AND source_type = #{stype}
            AND source_id = #{sid}
          ) min_ids
        )
      })
    end
31 32
  end
end