In Rails 5 (Official Docs) you can use the updated:
redirect_back(fallback_location: root_path)
Using this redirects the user to the referring page (previous page, the same as redirect_to :back
). If this isn't possible, it then redirects to a fallback location specified in the controller.
An example of a method in your controller (this redirects the user to the root path as a fallback location):
def some_method
#Your Code Here
redirect_back(fallback_location: root_path)
end
An example of a method for deleting an expense
and redirecting back, with a fallback to the root_path
:
def destroy
@expense.destroy
redirect_back(fallback_location: root_path)
end
Below are some other examples of the fallback_location
's that can be used to redirect the browser back to a specific page, if the referring page cannot be redirected to:
redirect_back fallback_location: "http://www.google.com" #Redirects to Google (or any website you specify)
redirect_back fallback_location: "/images/screenshot.jpg" #Redirects to a local image
redirect_back fallback_location: posts_path #Redirects to the 'posts' path
redirect_back fallback_location: new_user_path #Redirects to the new user path