Rails redirect_to post method?
I found a semi-workaround that I needed to make this happen in Rails 3. I made a route that would call the method in that controller that requires a post call. A line in "route.rb", such as:
match '/create', :to => "content#create"
It's probably ugly but desperate times call for desperate measures. Just thought I'd share.
The answer is that you cannot do a POST using a redirect_to
.
This is because what redirect_to
does is just send an HTTP 30x redirect header to the browser which in turn GETs the destination URL, and browsers do only GETs on redirects
It sounds like you are getting tripped up by how Rails routing works. This code:
redirect_to :controller=>'groups',:action=>'invite',:group_id=>@group_member.group_id
creates a URL that looks something like /groups/invite?group_id=1
.
Without the mapping in your routes.rb
, the Rails router maps this to the show
action, not invite
. The invite
part of the URL is mapped to params[:id]
and when it tries to find that record in the database, it fails and you get the message you found.
If you are using RESTful routes, you already have a map.resources
line that looks like this:
map.resources :groups
You need to add a custom action for invite
:
map.resources :groups, :member => { :invite => :get }
Then change your reference to params[:group_id]
in the #invite
method to use just params[:id]
.
The idea is to make a 'redirect' while under the hood you generate a form with method :post.
I was facing the same problem and extracted the solution into the gem repost
, so it is doing all that work for you, so no need to create a separate view with the form, just use the provided by gem function redirect_post()
on your controller.
class MyController < ActionController::Base
...
def some_action
redirect_post('url', params: {}, options: {})
end
...
end
Should be available on rubygems.