✌️

いっけな〜い!ついRailsでunsigned bigintなPRIMARY KEYにし忘れちゃった〜!☆(ゝω・)vキャピ

2024/04/30に公開

migrateしとき〜!

class ChangeIdTypeToUnsignedBigintOnAllTables < ActiveRecord::Migration[7.1]
  def up
    change_tables
  end

  def down
    change_tables(false)
  end

  private

  def change_tables(unsigned = true)
    Rails.application.eager_load!
    tables = ActiveRecord::Base.connection.tables

    ApplicationRecord.descendants.each do |model|
      parent = model.table_name
      children = []

      tables.each do |table|
        ActiveRecord::Base.connection.foreign_keys(table).filter { _1.to_table == parent }.each do |fk|
          children.push({ column: fk.column, table: })
        end
      end

      children.each do |child|
        child => { column:, table: }
        remove_foreign_key(table, parent, column:)
      end

      change_column(parent, :id, :bigint, unsigned:)

      children.each do |child|
        child => { column:, table: }
        change_column(table, column, :bigint, unsigned:)
        add_foreign_key(table, parent, column:)
      end
    rescue ActiveRecord::StatementInvalid
      next
    end
  end
end

より良い書き方ありましたらご指摘ください!!!!!

Discussion