class GameParticipant < ApplicationRecord belongs_to :game belongs_to :user validates :status, inclusion: { in: %w[joined ready finished] } validates :user_id, uniqueness: { scope: :game_id } validates :power, uniqueness: { scope: :game_id }, allow_nil: true # ステータス管理メソッド def joined? status == 'joined' end def ready? status == 'ready' end def finished? status == 'finished' end # パワー選択関連 def has_selected_power? power.present? end def select_power!(power_name) update!(power: power_name, status: 'ready') end # ゲーム参加メソッド class << self def join_game!(game, user, password = nil) # パスワードチェック(プレイヤーモードの場合) if game.player_mode? && game.password.present? raise "Invalid password" unless game.password == password end # 既存参加チェック if game.game_participants.exists?(user_id: user.id) raise "Already joined this game" end # 定員チェック if game.player_mode? && game.full? raise "Game is full" end create!(game: game, user: user, joined_at: Time.current, status: 'joined') end end end