views:

179

answers:

4

At the end of one of my controller actions I need to redirect to a page that only accepts put requests. I have been trying to figure out how to get redirect_to to use a put request but to no success.

Is this possible? Or is there another way to accomplish this?

Thanks.

+1  A: 

You could redirect to a different page that issues the put request from the client, using Javascript.

cdonner
+2  A: 

I don't think you are able to do this, and I suspect that the limitation is part of HTTP itself.

When using redirect_to - the redirection happens as a "302 Moved" header unless otherwise specified in the parameters.

Having a look at the HTTP Spec itself doesn't reveal any way to change the type of request the browser makes via redirect.

HTTP Redirects:

This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD.

I think you may need to use JavaScript to achieve this functionality, or perhaps rethink the flow of control in your application.

Toby Hede
A: 

If the action is in the same controller as where you're trying to redirect from, simply call the action and render the template like so:

def show
  index
  render :action => "index"
end

If it's not, then I don't know how you do that.

Ryan Bigg
+1  A: 

Ok, so I found a solution to my problem. I found a very good write up on the situation here. My implementation looks like this:

private
def redirect_post(redirect_post_params)
  controller_name = redirect_post_params[:controller]
  controller = "#{controller_name.camelize}Controller".constantize
  # Throw out existing params and merge the stored ones
  request.parameters.reject! { true }
  request.parameters.merge!(redirect_post_params)
  controller.process(request, response)
  if response.redirected_to
    @performed_redirect = true
  else
    @performed_render = true
  end
end

Then I called this method like this:

  redirect_post :controller => 'registrations', :action => 'order', :_method => 'put', :authenticity_token => params[:authenticity_token]

So I was able to 'fake' a put request by making a post request (using redirect_post) and then assigning 'put' to a _method param. If you look at a normal put request all it is a post from a form with a _method param. So its a bit hackish but it gets the job done.

Also, you have to make sure that when you call redirect_post the values of your hash are strings otherwise errors will be thrown.

vrish88