如何在 Rails 中为同一个表单创建多个提交按钮? [英] How do I create multiple submit buttons for the same form in Rails?
问题描述
我需要有多个提交按钮.
I need to have multiple submit buttons.
我有一个创建 Contact_Call 实例的表单.
I have a form which creates an instance of Contact_Call.
一个按钮可以正常创建.
One button creates it as normal.
另一个按钮创建它,但需要有一个与默认值不同的 :attribute 值,它还需要在控制器中使用的不同但相关的模型上设置属性.
The other button creates it but needs to have a different :attribute value from the default, and it also needs to set the attribute on a different, but related model used in the controller.
我该怎么做?我无法更改路线,那么有没有办法发送一个由 [:params] 获取的不同变量?
How do I do that? I can't change the route, so is there a way to send a different variable that gets picked up by [:params]?
如果我这样做了,我在控制器中做什么,设置一个 case 语句?
And if I do then, what do I do in the controller, set up a case statement?
推荐答案
您可以创建多个提交按钮并为每个按钮提供不同的值:
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.
这篇关于如何在 Rails 中为同一个表单创建多个提交按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!