Monday, November 6, 2017

Redirection to a GET after a PUT in Rails (status: 303) not working

Leave a Comment

In Rails 5.1, I'm doing a PUT, and trying to redirect on a certain error:

  rescue_from ActionController::InvalidAuthenticityToken do     redirect_to new_user_session_url, status: 303 and return   end 

The docs show that status: 303 should make the redirect_to be called as a GET, but it's still a PUT.

How can I make this redirect as a GET?

Thanks

3 Answers

Answers 1

If you are doing it with Ajax, your request is processing as JS , then your redirect shouldn't work, because you need yo get a response in your complete through Ajax call.

Finally, you should redirect within the complete callback sending the URL with your controller.

I Hope that helps you

Answers 2

You're request isn't http so the status will not work. Change your redirect to the following: render :js => "window.location = '/users/signup'" or whatever yournew_user_session_path` url is.

Answers 3

I could make PUT redirect work in browser and in curl

# Gemfiile gem 'rails' gem 'pry' gem 'puma'   # app.rb require 'rails' require 'action_controller' require 'rack/handler/puma'  class InvalidAuthenticityToken < StandardError end  # HelloController class HelloController < ActionController::Base   def index     render inline: ' <form action="/" method="POST">   <input type="hidden" name="_method" value="put" />   First name:<br>   <input type="text" name="firstname" value="Mickey">   <br>   Last name:<br>   <input type="text" name="lastname" value="Mouse">   <br><br>   <input type="submit" value="Submit"> </form>     '   end    def update     raise InvalidAuthenticityToken   end    def redirect     render plain: 'you are redirected'   end    rescue_from InvalidAuthenticityToken do     redirect_to '/you_are_redirected'   end end  class MyApp < Rails::Application end  app = MyApp.new app.config.secret_key_base = 'my-secret' app.initialize! app.routes.draw do   get '/' => 'hello#index'   get '/you_are_redirected' => 'hello#redirect'   put '/' => 'hello#update'   put '/you_are_redirected' => 'hello#redirect'   post '/you_are_redirected' => 'hello#redirect' # for browser request end  Rack::Handler::Puma.run app 

To run it

bundle bundle exec ruby app.rb 

visit localhost:9292 or

curl -X PUT localhost:9292 -L  you are redirected% 

I wish it helped

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment