20241104151855_issue5390_taskbar_remove_duplicated_key_by_user.rb 795 B

1234567891011121314151617181920212223
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Issue5390TaskbarRemoveDuplicatedKeyByUser < 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. return if duplicates.blank?
  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. end