搜索时“找不到没有 ID 的游戏”

'Couldn't find Game without an ID' when searching

我试图让用户搜索 API 但我收到以下错误:

“没有 ID 找不到游戏”

这是我的控制器:

class GamesController < ApplicationController

  def index
    @games = Game.all
  end

  def create
    @game = Game.new(game_params)
  end

  def show
  end

  def search
    @games = Game.find(params[:id])
    game = GiantBomb::Game.name
  end

  def new
    @game = Game.new
  end

  def edit
  end

private

  def game_params
    params.require(:game).permit(:name)
  end
end

我的路线:

Rails.application.routes.draw do
  devise_for :users
  resources :games
  root to: 'pages#home'
  post '/search', to: 'games#search', as: :search
end

我认为不太可能是我的搜索表单导致了这个错误,但无论如何它是这样的:

<div class="col-md-12">
          <%= form_tag search_path class: "row", method: :get do %>
          <div class="col-12 col-sm pr-sm-0">
            <%= text_field_tag :game,
              params[:game],
              class: "form-control input-lg",
              id: "typed-text" %>
          </div>
          <div class="input-group-btn ml-3">
            <%= submit_tag "Search", class: "btn btn-primary" %>
          </div>
          <% end %>

我是否需要更改路线,或者我编写控制器的方式有问题吗?

所以您收到该错误是因为当您到达 def search 方法时 params[:id] 不存在。在某事上调用 .find 将始终导致引发异常,除非找到某事。如果这是有意的,那么很酷,否则将其更改为 .find_by id: params[:id]。这将导致您的 @games 变量为零。

我认为您正试图在 params[:game] 上进行搜索。在这种情况下,您可能必须使用 @games = Game.find_by game: params[:game]

您可以在日志中看到哪些参数被传递给了您的方法。但是可能值得附加一个调试器;例如 byebug 到方法的顶部,这样您就可以看到存在哪些参数。