如何在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.