首页 > 解决方案 > 由于 PATCH 路由错误,无法更新实例

问题描述

我正在尝试更新游戏实例,但即使我正在为游戏提供所有资源,我也会收到路由错误。

Started PATCH "/games" for ::1 at 2020-01-16 20:18:21 -0500
ActionController::RoutingError (No route matches [PATCH] "/games"):

这是我的路线.rb

Rails.application.routes.draw do
  resources :games
end

这是我在游戏控制器中的更新方法

  def update
    game = Game.find_by(id: params[:id])

    if game.update(game_params)
      render json: { message: "Accepted initials." }
    else
      render json: { message: "Didn't accept initials" },
      status: :not_acceptable
    end
  end

  private

  def game_params
    params.require(:game).permit(
      :score,
      :initials,
      :total_calories
    )
  end

如果有帮助,这是我的 fetch PATCH 请求

fetch("http://localhost:3000/games", {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify({
        game: {
          score: this.props.state.currentGame.score,
          initials: this.state.initials,
          total_calories: this.props.state.currentGame.total_calories
        }
      })
    });

标签: ruby-on-railsruby

解决方案


您的补丁路线是“ http://localhost:3000/games/:id ”,而不是“ http://localhost:3000/games ”。
所以应该是...

fetch("http://localhost:3000/games/" + "<find a way to get game id>", {

推荐阅读