BigW Consortium Gitlab

20160603180330_remove_duplicated_notification_settings.rb 870 Bytes
Newer Older
1
# rubocop:disable all
2 3
class RemoveDuplicatedNotificationSettings < ActiveRecord::Migration
  def up
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 31
    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
32 33
  end
end