20241106073757_taskbar_add_uniqueness_index.rb 901 B

12345678910111213141516171819202122232425262728
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class TaskbarAddUniquenessIndex < ActiveRecord::Migration[7.1]
  3. def change
  4. return if !Setting.exists?(name: 'system_init_done')
  5. duplicates = Taskbar.select(:user_id, :app, :key).group(:user_id, :app, :key).having('COUNT(*) > 1').reorder(nil)
  6. if duplicates.exists?
  7. Taskbar
  8. .where(
  9. user_id: duplicates.pluck(:user_id),
  10. app: duplicates.pluck(:app),
  11. key: duplicates.pluck(:key)
  12. )
  13. .group_by { |taskbar| [taskbar.user_id, taskbar.app, taskbar.key] }
  14. .each_value do |records|
  15. newest_record = records.max_by(&:last_contact)
  16. records.reject { |record| record == newest_record }.each(&:destroy)
  17. end
  18. end
  19. add_index :taskbars, %i[user_id key app], unique: true
  20. Taskbar.reset_column_information
  21. end
  22. end