使用 put 方法通过 rails form_tag 上的按钮发送参数

Sending parameters through button on rails form_tag with put method

我有两个链接(如果需要可以是按钮)表示接受和拒绝,我需要通过单击其中一个链接向我的控制器操作发送 true 或 false 参数。我不希望我的参数在 url 中可见,所以我需要使用 put 方法。我尝试使用 link_to 定义的方法:

<%= link_to 'accept', { action: 'accept_offer', accept: true }, method: :put %>
<%= link_to 'decline', { action: 'accept_offer', accept: false }, method: :put %>

但我的参数仍然可见。

我试过使用 button_to 但是我的参数没有被传递。 在不显示 url 中的参数的情况下确定已选择哪个选项(接受或拒绝)的最佳方法是什么?

我的路线定义如下:

put 'offers', to: 'offers#accept_offer'

从常规路线开始:

resources :offers

然后让我们使用button_to创建一个离散形式:

<%= button_to 'accept', @offer, method: :patch, params: { "offer[accept]" =>  true } %>
<%= button_to 'decline', @offer, method: :patch, params: { "offer[accept]" => false } %>

params 选项在表单内创建隐藏输入。

然后确保将正确的属性列入白名单:

class OffersController < ApplicationController
  def update
    @offer = Offer.find(params[:id])

    if @offer.update(offer_params)
      redirect_to @offer, success: 'Offer updated'
    else
      render :new
    end
  end

  def offer_params
     params.require(:offer).permit(:accept, :foo, :bar)
  end
end

如果您需要与常规更新分开的逻辑,请创建两个额外的动词:

resources :offers do
  member do
    patch :accept
    patch :decline
  end
end

<%= button_to 'accept', accept_offer_path(@offer), method: :patch %>
<%= button_to 'decline', decline_offer_path(@offer), method: :patch %>

这让您的 API restful 和描述性。

我建议制作一个表单而不是 link_to 并在名称中传递参数。使用表单和 POST information.This 可能需要源页面中的额外代码,但不应要求目标页面中的逻辑更改。

<% form_for @offer, :url => {:action => 'accept_offer'} do |f|%>
  <%= submit_tag "", :value => "Accept", :name => "accept" %>
  <%= submit_tag "", :value => "Decline", :name => "decline"  %>
<% end %>

在您的操作中,您将根据您点击的 link 获得 params[:accept] 或 params[:decline]。

编辑为在提交标签上包含带有关键字参数的逗号和空格。]