How do I create multiple submit buttons for the same form in Rails? How do I create multiple submit buttons for the same form in Rails? ruby ruby

How do I create multiple submit buttons for the same form in Rails?


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 %>

This will output:

<input type="submit" value="A" id=".." name="commit" /><input type="submit" value="B" id=".." name="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    endend

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


There is also another approach, using the formaction attribute on the submit button:

<% form_for(something) do |f| %>    ...    <%= f.submit "Create" %>    <%= f.submit "Special Action", formaction: special_action_path %><% end %>

The code stays clean, as the standard create button doesn't need any change, you only insert a routing path for the special button:

formaction:
The URI of a program that processes the information submitted by the input element, if it is a submit button or image. If specified, it overrides the action attribute of the element's form owner. Source: MDN


You can alternatively recognized which button was pressed changing its attribute name.

<% form_for(something) do |f| %>    ..    <%= f.submit 'A', name: 'a_button' %>    <%= f.submit 'B', name: 'b_button' %>    ..<% end %>

It's a little bit uncomfortable because you have to check for params keys presence instead of simply check params[:commit] value: you will receive params[:a_button] or params[:b_button] depending on which one was pressed.