Gracefully handling InvalidAuthenticityToken exceptions in Rails 4

前端 未结 3 1116
北恋
北恋 2021-02-04 02:39

I\'ve just upgraded an app from Rails 3 to Rails 4, and I\'m seeing a bunch of InvalidAuthenticityToken exceptions popping up. Digging in it looks like it is fairly common for o

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 02:45

    In my rails 4.1.1 app I had the same problem. I solved it by adding this code to ApplicationController. I found this solution here.

    rescue_from ActionController::InvalidAuthenticityToken, with: :redirect_to_referer_or_path
    
    def redirect_to_referer_or_path
      flash[:notice] = "Please try again."
      redirect_to request.referer
    end
    

    This way any controller that inherits from ApplicationController will handle the error with a redirect to the page the form was submitted from with a flash message to give the user some indication of what went wrong. Note this uses the hash syntax introduced in Ruby 1.9. For older versions of Ruby you will need to use :with => :redirect_to_referer_or_path

提交回复
热议问题