Form_for with multiple controller actions to submit

How to pass url in form_for submit? I am trying to use one form with each button indicating the actions of each controller, one is a search and the other is a creation. Is it possible to have two submit buttons with different actions in the same form?

<%= form_for @people do |f| %> <%= f.label :first_name %>: <%= f.text_field :first_name %><br /> <%= f.label :last_name %>: <%= f.text_field :last_name %><br /> <%= f.submit(:url => '/people/search') %> <%= f.submit(:url => '/people/create') %> <% end %> 
+7
source share
2 answers

There is no easy way for Rails to submit forms to different URLs depending on the button clicked. You can use javascript on each button to send to different URLs, but a more common way to deal with this situation is to let the form send to one URL and determine which button was clicked in the controller action.

For the second approach with submit buttons:

 <%= form_for @people do |f| %> # form fields here <%= submit_tag "First Button", :name => 'first_button' %> <%= submit_tag "Second Button", :name => 'second_button' %> <% end %> 

Your action will look something like this:

 def create if params[:first_button] # Do stuff for first button submit elsif params[:second_button] # Do stuff for second button submit end end 

See this similar question for more details on both approaches.

Also, see the Railscast 38 episode in multibyte forms.

+20
source

This question is very similar to this one , although it is slightly different

I just wanted to emphasize that some answer to the above question also suggested adding restrictions to the routes, so you can send requests to various actions of the controller!

Credits to the author, vss123

We decided to use advanced restrictions in rails.

The idea is to have the same path (and therefore the same named route & action), but with routing restrictions on different actions.

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

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

It is available as a commit_param_matching gem.

+2
source

All Articles