Answers:
form_for @user, :url => url_for(:controller => 'mycontroller', :action => 'myaction')
要么
form_for @user, :url => whatever_path
以下对我有用:
form_for @user, :url => {:action => "YourActionName"}
action:
(动作冒号)api.rubyonrails.org/classes/ActionView/Helpers
form_for @user, url: {action: 'myaction'}
但这给了我No route matches {:action=>"myaction", :controller=>"users"}
错误。
resources :users do
collection do
get :myaction
end
end
我是那样做的
<%= form_for :user, url: {action: "update", params: {id: @user.id}} do |f| %>
请注意,将可选参数id
设置为用户实例id属性。
另外,可以使用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中所述
@user
。使用form_tag
不会将对象的属性绑定到表单字段。
如果要在渲染部分表单时将自定义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| -%>
url_for
没有必要。另外,由于控制器是相同的,因此您可以使用form_for @user, :url => :action => 'myaction'