form_for with multiple controller actions for submit

magnifying glass on a square f picture magnifying glass on a square f · Aug 13, 2011 · Viewed 12.8k times · Source

How do I pass a url on the form_for submit? I'm trying to use one form with each buttons pointing to each controller actions, one is search and another one is create. Is it possible to have 2 submit buttons with different actions on 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 %>

Answer

Troy picture Troy · Aug 13, 2011

There is not a simple Rails way to submit a form to different URLs depending on the button pressed. You could use javascript on each button to submit to different URLs, but the more common way to handle this situation is to allow the form to submit to one URL and detect which button was pressed in the controller action.

For the second approach with a submit buttons like this:

<%= 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 would 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 about both approaches.

Also, see Railscast episode 38 on multibutton forms.