Ruby on rails:在同一表单上有多个submit_tag

时间:2013-10-21 16:43:50

标签: ruby-on-rails ruby

如何在同一表单上设置多个submit_tag按钮? 现在我只使用一个按钮,但我不知道如何让form_tag处理多个路径。

的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 %>

请指教。 提前谢谢。

1 个答案:

答案 0 :(得分:2)

我不知道你能否走上不同的道路。但这会有所帮助吗?

只需执行一个操作,然后根据单击的提交按钮在控制器中执行操作。您的路线看起来像

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

您将查看

<%= 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 %>

在您的控制器中

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