1

如何在同一个表单上有多个 submit_tag 按钮?现在我只为一个按钮工作,但我不确定如何让 form_tag 处理多个路径。

路由.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' 

开始.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 %>

请指教。先感谢您。

4

1 回答 1

3

我不知道你是否可以让它走不同的道路。但是这样的事情会有帮助吗?

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

*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
于 2013-10-21T16:58:47.793 回答