且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Rails 中为同一个表单创建多个提交按钮?

更新时间:2023-11-24 10:40:52

您可以创建多个提交按钮并为每个按钮提供不同的值:

You can create multiple submit buttons and provide a different value to each:

<% form_for(something) do |f| %>
    ..
    <%= f.submit 'A' %>
    <%= f.submit 'B' %>
    ..
<% end %>

这将输出:

<input type="submit" value="A" id=".." name="commit" />
<input type="submit" value="B" id=".." name="commit" />

在您的控制器中,提交按钮的值将由参数 commit 标识.检查值以进行所需的处理:

Inside your controller, the submitted button's value will be identified by the parameter commit. Check the value to do the required processing:

def <controller action>
    if params[:commit] == 'A'
        # A was pressed 
    elsif params[:commit] == 'B'
        # B was pressed
    end
end

但是,请记住,这将您的视图与控制器紧密耦合,这可能不是很理想.

However, remember that this tightly couples your view to the controller which may not be very desirable.