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

Ruby on Rails中如何根据用户输入的特定code重定向到对应Game页面?

解决方案:通过Game Code跳转至对应游戏页面

1. 补充路由配置

当前路由文件中未定义redirect_path,表单提交会报错。需添加对应路由(表单默认用POST提交,因此配置POST路由):

Rails.application.routes.draw do
  get 'welcome/index'
  resources :games
  # 添加对应WelcomeController的redirect动作路由
  post 'welcome/redirect', as: :redirect
  root 'welcome#index'
end

注:resources :games已自动生成games#index路由,原代码中的get 'games/index'可删除

2. 完善WelcomeController的redirect动作

根据用户输入的code查找游戏,处理找到/未找到两种场景:

class WelcomeController < ApplicationController
  def index
  end

  def redirect
    # 获取用户输入的code并去除首尾空格
    game_code = params[:param].strip
    # 根据code查找单个游戏对象(用find_by而非where,因为我们需要单个结果)
    game = Game.find_by(code: game_code)
    
    if game
      # 找到游戏则跳转到对应详情页
      redirect_to game_path(game)
    else
      # 未找到则返回首页并提示错误
      flash[:alert] = "未找到对应code的游戏"
      redirect_to root_path
    end
  end
end

3. (可选)优化表单参数名

将表单的参数名改为更语义化的game_code,提升代码可读性:

修改welcome/index.html.erb:

<h1>Let's join the game!</h1>

<%= form_tag redirect_path do %>
   <%= text_field_tag(:game_code, placeholder: "输入游戏Code") %>  
   <%= submit_tag("搜索") %>
<% end %>

同步更新WelcomeController的参数获取:

game_code = params[:game_code].strip

4. 确认Game模型的code字段存在

如果还未给Game模型添加code字符串字段,需执行迁移:

rails generate migration AddCodeToGames code:string
rails db:migrate

额外提示

若要给用户展示错误/成功提示,可在application.html.erb中添加flash消息渲染代码:

<% if flash[:alert] %>
  <div class="alert alert-danger"><%= flash[:alert] %></div>
<% end %>
<% if flash[:notice] %>
  <div class="alert alert-success"><%= flash[:notice] %></div>
<% end %>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:55:27