form_for but to post to a different action

Ruby on-Rails

Ruby on-Rails Problem Overview


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

How can I do this?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

or

form_for @user, :url => whatever_path

Solution 2 - Ruby on-Rails

The following works for me:

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

Solution 3 - Ruby on-Rails

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.

Solution 4 - Ruby on-Rails

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

Solution 5 - Ruby on-Rails

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

Solution 6 - Ruby on-Rails

new syntax

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlankmanView Question on Stackoverflow
Solution 1 - Ruby on-RailsAustinView Answer on Stackoverflow
Solution 2 - Ruby on-RailsPeter LeeView Answer on Stackoverflow
Solution 3 - Ruby on-RailsSzymon BłaszczyńskiView Answer on Stackoverflow
Solution 4 - Ruby on-RailsAditya Anand KrishnaView Answer on Stackoverflow
Solution 5 - Ruby on-RailsjuliangonzalezView Answer on Stackoverflow
Solution 6 - Ruby on-RailsgsumkView Answer on Stackoverflow