Search code examples
ruby-on-railshttp-redirecthttp-request

How do can you make redirect_to use a different HTTP request?


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?


Solution

  • 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.