【问题标题】:How to send [:commit] param with remote: true form_for如何使用远程发送 [:commit] 参数:true form_for
【发布时间】:2020-02-04 02:38:11
【问题描述】:

我有一个表单,我需要有 2 个提交按钮。这似乎是我能想到的实现我想要的唯一方法。

目标是使用一种表单发送到一个方法,然后根据传递的参数可能重定向到另一个方法,因为功能会有所不同。

表格:

<%= form_for(:mass, url: mass_product_variant_category_path, method: :get, remote: true) do |mass| %>
    <%= mass.submit "Update All", name: "All", class: "btn btn-light" %>
    <%= mass.submit "Update Files", name: "Files", class: "btn btn-light" %>
    <% @Stuff.each do |variant| %>
       <%= check_box_tag 'store_variant_ids[]', variant.id %>
    <% end %>
    ...
<% end %>

我试过了:&lt;%= submit_tag "Submit", name: "All" %&gt;,还是不行。

html:

&lt;input type="submit" name="File" value="Update Files" class="btn btn-light" data-disable-with="Update Files"&gt;

控制器:

def mass_product_variant_category
   @stuff = Stuff.where(store_variant_id: params[:store_variant_ids])
   if params[:commit] == "File"
     redirect_to edit_multiple_stuffs_path(stuffs: @stuffs)
   else
     respond_to do |format|
       format.js
     end
   end
end

传递的参数是:

{..."mass" =&gt; {hidden_field: "int"}, "other_attributes" =&gt; ["int"]...}

这是由于使用了remote: true,但不确定原因或方式。

如何根据提交表单传递参数?

我已经阅读了其他关于此的 SO 帖子,但很少,而且似乎没有一个很好或任何可接受的答案。由于需要基于使用的提交按钮进行重定向,我也无法使用 hidden_​​fields。

是否有一种“Rails”方式可以做到这一点而无需添加 javascript,或者这是我唯一的选择吗?

【问题讨论】:

  • 我不确定是否有多次提交,但你为什么不添加一个带有两个单选按钮的字段,称为“全部更新”和“更新文件”(默认选择一个),然后只添加一个提交按钮。单选按钮根据选择将commit 参数设置为“全部”或“文件”,您将获得所需的功能。会有帮助吗?如果它对您有用,但您对如何使用感到困惑,我将添加一个带有表单代码的答案。
  • 这是个好主意。我最终设置了一个隐藏字段标签,该标签通过 onclick 接受基于提交按钮的参数

标签: javascript ruby-on-rails ruby


【解决方案1】:

我通过在表单中​​使用hidden_field_tag 解决了这个问题,该表单根据通过点击使用的提交按钮填写。然后我可以检查控制器中的 hidden_​​fields 参数。

【讨论】:

    【解决方案2】:

    “name”属性映射到params 散列中的名称。对于这种情况,您应该执行以下操作:

    if params["File"]
      # Something
    elsif params["All"]
      # Other thing
    else
      # Default
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 2011-06-26
      • 2014-11-18
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      相关资源
      最近更新 更多