学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Rails7.0 | Railsでゲームを作成 | 19 | backendの設定

18 | スコアボード】 << 【ホーム】 >> 【20 | APIテスト


↓↓クリックして頂けると励みになります。


backend(Rails側)の設定を進めていきます。

ルートの設定



「config/routes.rb」ファイルを編集します。


記述編集 【Desktop/RailsGame/backend/config/routes.rb】

Rails.application.routes.draw do
  # API
  namespace :api do
    namespace :v1 do
      resources :games, :players, only: [:index, :create]
    end
  end
end



モデルの編集

「app/models/game.rb」ファイルを編集します。


記述編集 【Desktop/RailsGame/backend/app/models/game.rb】

class Game < ApplicationRecord
    belongs_to :player
  
    scope :top_five, -> { order("score desc").limit(5) }
  end



コントローラの設定

「app/controllers」フォルダの中に「api」フォルダを新規作成します。
作成した「api」フォルダの中に「v1」フォルダを新規作成します。
作成した「v1」フォルダの中に「players_controller.rb」ファイルを新規作成します。



新規作成 【Desktop/RailsGame/backend/app/controllers/api/v1/players_controller.rb】

class Api::V1::PlayersController < ApplicationController
  def index
    players = Player.all
    render json: players
  end

  def create
    player = Player.find_or_create_by(username: params[:username].upcase)
    render json: player
  end
end



作成した「api/vi」フォルダの中に、「games_controller.rb」ファイルを新規作成します。


新規作成 【Desktop/RailsGame/backend/app/controllers/api/v1/games_controller.rb】

class Api::V1::GamesController < ApplicationController
    def index
      top_scores = Game.top_five
      render json: top_scores, only: [:score], include: { player: { only: [:id, :username] } }
    end
  
    def create
      begin
        # params で渡されたユーザー名を持つプレーヤーを検索します
        player = Player.find_by(username: params[:username].upcase)
        new_score = params[:score]
  
        # そのプレイヤーがいるゲームを探します
        game = Game.find_by(player_id: player.id)
  
        if game
          # 新しいスコアが既存のスコアより大きい場合は更新します
          if game.score < new_score
            game.score = new_score
            game.save
          end
        else
          # 新しいゲームを作成する
          Game.create(player_id: player.id, score: new_score)
        end
  
        top_scores = Game.top_five
        render json: top_scores, only: [:score], include: { player: { only: [:id, :username] } }
  
      rescue Exception
        render json: {message: "ゲームを保存できません"}, status: 400
      end
    end
  end
  


コントローラファイル作成
コントローラファイル作成


↓↓クリックして頂けると励みになります。


18 | スコアボード】 << 【ホーム】 >> 【20 | APIテスト