user2904022
user2904022

Reputation: 13

Ruby on rails: Multiple submit_tag on the same form

How can I have multiple submit_tag buttons on the same form? For now I got it working only for one button, but I'm not sure how to get form_tag to handle multiple paths.

Routes.rb

  resources :actions do
  end
  root 'home#start'
  match '/home/add', to: 'home#add', via: 'get'
  match '/home/subtract', to: 'home#subtract', via: 'get'
  match '/home/multiply', to: 'home#multiply', via: 'get' 

Start.html.erb

 <%= form_tag "/home/add",:method => "get" do %>
 <p></p>
 <p>
 <%= label_tag :entered, "Please enter value:" %> </br>
 <%= text_field_tag :entered %>
 </p>
 <p></p>
 <p>
 <%= label_tag :entered2, "Please enter value:" %> </br>
 <%= text_field_tag :entered2 %>
 </p>
 <%= submit_tag "add", :controller => "home", :action => "add" %>
 <%= submit_tag "subtract",  :controller => "home", :action => "subtract" %>
 <%= submit_tag "multiply", :controller => "home", :action => "multiply"%>
 <% end %>

Please advise. Thank you in advance.

Upvotes: 1

Views: 1994

Answers (1)

usha
usha

Reputation: 29349

I don't know if you can make it go to different path. But would something like this help?

Just have one action and do stuff in your controller based on the submit button that was clicked. You routes will look like

*Routes.rb*
  resources :actions do
  end
  root 'home#start'
  match '/home/operation', to: 'home#add', via: 'get'

You view will be

<%= form_tag "/home/operation",:method => "get" do %>
 <p></p>
 <p>
 <%= label_tag :entered, "Please enter value:" %> </br>
 <%= text_field_tag :entered %>
 </p>
 <p></p>
 <p>
 <%= label_tag :entered2, "Please enter value:" %> </br>
 <%= text_field_tag :entered2 %>
 </p>
 <%= submit_tag "Add"%>
 <%= submit_tag "Subtract"%>
 <%= submit_tag "Multiply"%>
 <% end %>

In your controller

class HomeController < ApplicationController
  def operation
    send(params[:commit].downcase) #params[:commit] will have one of the values "Add", "Subtract", "Multiply"
  end

  private
  def add
    #do something
  end

  def subtract
   #do something
  end

  def multiple
   #do something
  end
end

Upvotes: 3

Related Questions