form_for带有多个提交的控制器动作 [英] form_for with multiple controller actions for submit

查看:67
本文介绍了form_for带有多个提交的控制器动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在form_for提交中传递一个URL?我正在尝试使用一种形式,其中每个按钮都指向每个控制器动作,一种是搜索,另一种是创建.是否可以在同一表单上有2个提交按钮,它们具有不同的操作?

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

解决方案

根据所按下的按钮,没有一种简单的Rails方法可以将表单提交到不同的URL.您可以在每个按钮上使用javascript提交到不同的URL,但是处理这种情况的更常见方法是允许表单提交到一个URL并检测控制器操作中按下了哪个按钮.

对于第二种使用提交按钮的方法,如下所示:

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

您的操作将如下所示:

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

有关这两种方法的更多信息,请参见类似的问题. /p>

此外,请参见多播表单上的第38集铁路广播.

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

解决方案

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.

这篇关于form_for带有多个提交的控制器动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆