Before Rails 4.x
to easily navigate back once the action is complete we used to use redirect_to :back
method that looks something like this:
class OrdersController < ApplicationController
def approve
order = Order.find params[:id]
order.approve!
redirect_to :back
end
end
This action will approve the order and redirect the user to the previous location where he performed this action from. However, if this action was performed and the HTTP_REFERER
is missing, which can lead to ActionController::RedirectBackError
exception to be raised.
Rescue the exception
One way to solve this method is to rescue
the Exception and redirect to the default location.
class OrdersController < ApplicationController
rescue_from ActionController::RedirectBackError, with: :redirect_to_default
def approve
order = Order.find params[:id]
order.approve!
redirect_to :back
end
private
def redirect_to_default
redirect_to orders_path
end
end
Using redirect_back
After Rails 5.x, we can use redirect_back it accept fallback_location
as an argument where we can provide the fallback location if the HTTP_REFERER
is empty.
class OrdersController < ApplicationController
def approve
order = Order.find params[:id]
order.approve!
redirect_back fallback_location: orders_path
end
end