You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails+React游戏应用如何通过POST请求存储用户高分数据到数据库

完整实现流程

一、Rails 后端接口开发

1. 创建得分数据模型

  • 执行生成模型命令:rails generate model Score username:string score:integer
  • 执行数据库迁移:rails db:migrate
  • 在app/models/score.rb中新增验证规则+最近5条数据清理逻辑:
class Score < ApplicationRecord
  validates :username, presence: true
  validates :score, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
  # 新增数据后自动清理超出5条的历史数据
  after_create :keep_only_latest_5

  private
  def keep_only_latest_5
    user_all_scores = Score.where(username: self.username).order(created_at: :desc)
    user_all_scores.offset(5).destroy_all if user_all_scores.count > 5
  end
end

2. 配置路由与控制器

  • 在config/routes.rb中新增接口路由:
Rails.application.routes.draw do
  # 保留你现有其他路由
  resources :scores, only: [:create, :index]
end
  • 新建app/controllers/scores_controller.rb实现接口逻辑:
class ScoresController < ApplicationController
  # 前后端分离场景可关闭CSRF校验,生产环境建议替换为token校验方案
  skip_before_action :verify_authenticity_token

  # 拉取全量得分数据接口,供前端高分榜排序使用
  def index
    scores = Score.order(created_at: :desc)
    render json: scores, status: :ok
  end

  # 提交得分入库接口
  def create
    score = Score.new(score_params)
    if score.save
      render json: score, status: :created
    else
      render json: { errors: score.errors.full_messages }, status: :unprocessable_entity
    end
  end

  private
  def score_params
    params.require(:score).permit(:username, :score)
  end
end

3. 配置跨域规则(必做,否则前端请求会被拦截)

  • 在Gemfile中新增跨域依赖:gem 'rack-cors',执行bundle install安装
  • 在config/initializers/cors.rb中配置前端访问权限:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3001' # 替换为你实际React前端的访问地址
    resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

配置完成后重启Rails服务生效。

二、React 前端请求实现

1. 封装得分提交方法

可根据你的技术栈选择原生fetch或者axios实现:

原生fetch版本:

const submitScore = async (username, score) => {
  try {
    const res = await fetch('http://localhost:3000/scores', { // 替换为你实际Rails后端地址
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        score: {
          username: username,
          score: score
        }
      })
    })
    if (!res.ok) {
      const err = await res.json()
      throw new Error(err.errors.join(','))
    }
    // 提交成功后可自定义后续逻辑,比如跳转高分榜
    console.log('得分提交成功', await res.json())
  } catch (err) {
    console.error('提交失败:', err.message)
  }
}

axios版本:

先执行npm install axios安装依赖,再封装方法:

import axios from 'axios'

const submitScore = async (username, score) => {
  try {
    const res = await axios.post('http://localhost:3000/scores', {
      score: {
        username: username,
        score: score
      }
    })
    console.log('得分提交成功', res.data)
  } catch (err) {
    console.error('提交失败:', err.response?.data?.errors?.join(',') || err.message)
  }
}

2. 触发提交逻辑

在游戏结束的回调函数中调用上面封装的提交方法即可:

// 你的游戏结束触发逻辑
const handleGameOver = () => {
  const finalScore = getCurrentGameScore() // 替换为你自己的获取当前游戏得分逻辑
  const currentUser = getLoginUsername() // 替换为你自己的获取当前玩家用户名逻辑
  submitScore(currentUser, finalScore)
}

3. 高分榜拉取数据逻辑

需要展示高分榜时发送GET请求拉取全量数据,自行做排序展示即可:

const fetchScoreList = async () => {
  try {
    const res = await fetch('http://localhost:3000/scores')
    const scoreList = await res.json()
    // 拿到scoreList后自行实现排序、渲染逻辑
    console.log('得分列表', scoreList)
  } catch (err) {
    console.error('拉取得分失败', err)
  }
}

内容的提问来源于stack exchange,提问作者Kiana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 06:57:02