Ruby-on-rails form_for 但要发布到不同的操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5320414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:40:59  来源:igfitidea点击:

form_for but to post to a different action

ruby-on-rails

提问by Blankman

I want to have a form_for @user, but post to a custom action in the users controller.

我想要一个form_for @user, 但发布到用户控制器中的自定义操作。

How can I do this?

我怎样才能做到这一点?

回答by Austin

form_for @user, :url => url_for(:controller => 'mycontroller', :action => 'myaction')

or

或者

form_for @user, :url => whatever_path

回答by Peter Lee

The following works for me:

以下对我有用:

form_for @user, :url => {:action => "YourActionName"}

回答by Szymon B?aszczyński

I have done it like that

我已经这样做了

<%= form_for :user, url: {action: "update", params: {id: @user.id}} do |f| %>

Note the optional parameter idset to user instance id attribute.

请注意id设置为用户实例 id 属性的可选参数。

回答by juliangonzalez

Alternatively the same can be reached using form_tagwith the syntax:

或者,可以使用form_tag以下语法达到相同的目的:

form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_form")
# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">'

As described in http://guides.rubyonrails.org/form_helpers.html#multiple-hashes-in-form-helper-calls

http://guides.rubyonrails.org/form_helpers.html#multiple-hashes-in-form-helper-calls 中所述

回答by gsumk

new syntax

新语法

<%= form_for :user, url: custom_user_path, method: :post do |f|%>
<%end%>

回答by Aditya Anand Krishna

If you want to pass custom Controller to a form_for while rendering a partial form you can use this:

如果您想在渲染部分表单时将自定义控制器传递给 form_for,您可以使用以下命令:

<%= render 'form', :locals => {:controller => 'my_controller', :action => 'my_action'}%>

and then in the form partial use this local variable like this:

然后以部分形式使用这个局部变量,如下所示:

<%= form_for(:post, :url => url_for(:controller => locals[:controller], :action => locals[:action]), html: {class: ""} ) do |f| -%>