gpt4 book ai didi

ruby-on-rails - 当我包含查询字符串参数时,link_to 方法不会路由到 PATCH 请求

转载 作者:行者123 更新时间:2023-12-05 06:44:44 25 4
gpt4 key购买 nike

我正在尝试在 Rails View 中创建一个取消按钮,它链接到 PATCH/更新方法。我想传递一个查询字符串参数 -- update_action: "cancel"-- 因此更新方法知道这是一个取消操作并可以相应地处理它。这是取消按钮的 link_to 方法:

<%= link_to "Cancel", {controller: "/orders", action: "update", id: order.id, update_action: "cancel" }, method: "patch" %>

但是,当我执行此操作时,出现路由错误:

Unable to find route for [GET] order/update/id?update_action=cancel

出于某种原因,它试图路由到 GET 请求而不是 PATCH 请求。

现在,当我从 link_to 方法中删除查询字符串参数时,即

<%= link_to "Cancel", {controller: "/orders", action: "update", id: order.id }, method: "patch" %>

它正确地路由到 PATCH 订单/id,

当我包含查询字符串参数时,为什么我的 link_to 方法没有路由到 PATCH 请求?

注意,通过routes.rb文件包含:

resources :orders

最佳答案

你可以试一试,但我怀疑它是否会更好:

<%= link_to "Cancel", order_path(id: order.id, update_action: "cancel"), method: "patch" %>

Rails 中的路由是使用 RESTful 架构实现的。因此,您可以使用 GET 请求发送查询字符串参数。 PUT 请求通常不包含查询参数。这些参数在 request body 中提交(就像使用表单一样),如下例所示 guides

class ClientsController < ApplicationController
# This action uses query string parameters because it gets run
# by an HTTP GET request, but this does not make any difference
# to the way in which the parameters are accessed. The URL for
# this action would look like this in order to list activated
# clients: /clients?status=activated
def index
if params[:status] == "activated"
@clients = Client.activated
else
@clients = Client.inactivated
end
end

# This action uses POST parameters. They are most likely coming
# from an HTML form which the user has submitted. The URL for
# this RESTful request will be "/clients", and the data will be
# sent as part of the request body.
def create
@client = Client.new(params[:client])
if @client.save
redirect_to @client
else
# This line overrides the default rendering behavior, which
# would have been to render the "create" view.
render "new"
end
end
end

如果您只需要“取消”按钮,您可以使用与 GET 请求相同的路径。您的参数 {update_action:"cancel"} 将在 Controller 中可用。当您尝试获取/获取不同的页面时,它也很有意义。

PUT/PATCH 请求用于更新/创建模型中的数据,而 POST 用于创建。GET 请求将获取页面,或返回到之前的页面(就像在“取消”的情况下)。

关于ruby-on-rails - 当我包含查询字符串参数时,link_to 方法不会路由到 PATCH 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27799936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com