class CreateMatchPlayers < ActiveRecord::Migration[8.1] def change create_table :match_players do |t| t.string :match_uuid, null: false t.references :player, null: false, foreign_key: { to_table: :users } end add_foreign_key :match_players, :matches, column: :match_uuid, primary_key: :uuid add_index :match_players, :match_uuid add_index :match_players, [ :match_uuid, :player_id ], unique: true reversible do |dir| dir.up do execute <<~SQL INSERT INTO match_players (match_uuid, player_id) SELECT uuid, player1_id FROM matches UNION ALL SELECT uuid, player2_id FROM matches SQL end end end end