form_for but to post to a different action

后端 未结 6 2300
小蘑菇
小蘑菇 2020-12-02 05:08

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

How can I do this?

相关标签:
6条回答
  • 2020-12-02 05:51

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

    <%= 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| -%>
    
    0 讨论(0)
  • 2020-12-02 05:57
    form_for @user, :url => url_for(:controller => 'mycontroller', :action => 'myaction')
    

    or

    form_for @user, :url => whatever_path
    
    0 讨论(0)
  • 2020-12-02 06:08

    I have done it like that

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

    Note the optional parameter id set to user instance id attribute.

    0 讨论(0)
  • 2020-12-02 06:08

    Alternatively the same can be reached using form_tag with the syntax:

    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

    0 讨论(0)
  • 2020-12-02 06:09

    The following works for me:

    form_for @user, :url => {:action => "YourActionName"}
    
    0 讨论(0)
  • 2020-12-02 06:09

    new syntax

    <%= form_for :user, url: custom_user_path, method: :post do |f|%>
    <%end%>
    
    0 讨论(0)
提交回复
热议问题