Pages

Tuesday, January 7, 2014

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
    end
end
However, remember that this tightly couples your view to the controller which may not be very desirable.

No comments:

Post a Comment