20201006131231_stats_store_polymorphic_association.rb 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. class StatsStorePolymorphicAssociation < ActiveRecord::Migration[5.2]
  2. def change
  3. return if !Setting.exists?(name: 'system_init_done')
  4. # create ObjectLookup ID -> Model map
  5. object_lookup_map = ObjectLookup.all.pluck(:id, :name)
  6. # create empty, indexed polymorphic association columns
  7. add_reference :stats_stores, :stats_storable, polymorphic: true, index: true
  8. # set last run 20 min in future to avoid scheduler errors until restart
  9. Scheduler.find_by(method: 'Stats.generate').update(last_run: 20.minutes.from_now)
  10. # migrate column data in the most performance way
  11. object_lookup_map.each do |id, model|
  12. StatsStore.where(stats_store_object_id: id)
  13. .update_all("stats_storable_id = o_id, stats_storable_type = '#{model}'") # rubocop:disable Rails/SkipsModelValidations
  14. end
  15. remove_unneeded_columns
  16. end
  17. private
  18. def remove_unneeded_columns
  19. # remove home made "polymorphic association" columns
  20. remove_column :stats_stores, :o_id
  21. remove_column :stats_stores, :stats_store_object_id
  22. # remove unused/obsolete columns
  23. remove_column :stats_stores, :related_stats_store_object_id
  24. remove_column(:stats_stores, :related_o_id) if StatsStore.column_names.include?('related_o_id')
  25. end
  26. end