Rails: Multi-submit buttons in one Form Rails: Multi-submit buttons in one Form ruby-on-rails ruby-on-rails

Rails: Multi-submit buttons in one Form


This was covered in Railscast episode 38. Using the params hash to detect which button was clicked is the correct approach:

View:

<%= submit_tag 'Create' %><%= submit_tag 'Create and Add Another', name: 'create_and_add' %>

Controller:

if params[:create_and_add]  # Redirect to new form, for example.else  # Redirect to show the newly created record, for example.end


We solved using advanced constraints in rails.

The idea is to have the same path (and hence the same named route & action) but with constraints routing to different actions.

resources :plan do  post :save, constraints: CommitParamRouting.new("Propose"), action: :propose  post :save, constraints: CommitParamRouting.new("Finalize"), action: :finalizeend

CommitParamRouting is a simple class that has a method matches? which returns true if the commit param matches the given instance attr. value.

This available as a gem commit_param_matching.


it can also be done on the form_for helper like this

 <%= f.submit "Publish",name: "publish", class: "tiny button radius success" %> <%= f.submit 'Mark as Draft', name: "draft", class: "tiny button radius " %>

and the logic is the same on the controller

   if params[:publish]      // your code   elsif params[:draft]      // your code   end