form_for but to post to a different action

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

How can I do this?

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

或者

form_for @user, :url => whatever_path

下面这些对我有用:

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

I have done it like that

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

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

如果要在呈现部分表单时将自定义 Controller 传递给 form _ for,可以使用以下命令:

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

然后在表单的部分中使用这个局部变量,如下所示:

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

或者,也可以使用 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">'

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

新的语法

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