67 lines
2.5 KiB
Ruby
67 lines
2.5 KiB
Ruby
class BoardMembershipsController < ApplicationController
|
||
before_action :require_login
|
||
before_action :set_game
|
||
before_action :set_board
|
||
before_action :set_current_participant
|
||
|
||
def create
|
||
# メンバー追加処理
|
||
unless @board.negotiation? && @board.member?(@current_participant)
|
||
return redirect_to game_board_path(@game, @board), alert: "権限がありません"
|
||
end
|
||
|
||
target_participant_id = params[:participant_id]
|
||
|
||
# 重複チェック(既に参加しているか)
|
||
if @board.board_memberships.where(participant_id: target_participant_id, left_at: nil).exists?
|
||
return redirect_to game_board_path(@game, @board), alert: "そのプレイヤーは既に参加しています"
|
||
end
|
||
|
||
# 退出済みの場合は再参加(left_atをクリア)
|
||
membership = @board.board_memberships.find_by(participant_id: target_participant_id)
|
||
if membership
|
||
membership.update!(left_at: nil, joined_at: Time.current)
|
||
else
|
||
@board.board_memberships.create!(participant_id: target_participant_id, joined_at: Time.current)
|
||
end
|
||
|
||
# メンバー構成が変わったので、他の掲示板と重複していないかチェックが必要だが、
|
||
# モデルのバリデーションは「作成時」を想定しているため、ここでは簡易チェックに留めるか、
|
||
# あるいはバリデーションエラーをハンドリングする。
|
||
# ここではsave成功/失敗で判断
|
||
|
||
redirect_to game_board_path(@game, @board), notice: "メンバーを追加しました"
|
||
rescue ActiveRecord::RecordInvalid => e
|
||
redirect_to game_board_path(@game, @board), alert: "メンバー追加に失敗しました: #{e.message}"
|
||
end
|
||
|
||
def leave
|
||
# 退出処理
|
||
unless @board.negotiation? && @board.member?(@current_participant)
|
||
return redirect_to game_board_path(@game, @board), alert: "退出できません"
|
||
end
|
||
|
||
membership = @board.board_memberships.find_by(participant: @current_participant)
|
||
if membership
|
||
membership.leave!
|
||
redirect_to game_boards_path(@game), notice: "掲示板から退出しました"
|
||
else
|
||
redirect_to game_board_path(@game, @board), alert: "退出に失敗しました"
|
||
end
|
||
end
|
||
|
||
private
|
||
|
||
def set_game
|
||
@game = Game.find(params[:game_id])
|
||
end
|
||
|
||
def set_board
|
||
@board = @game.boards.find(params[:board_id])
|
||
end
|
||
|
||
def set_current_participant
|
||
@current_participant = @game.participants.find_by(user: current_user)
|
||
end
|
||
end
|