redirect_back vs redirect_to :back

I am a full-stack Ruby on Rails developer with experience in PostgreSQL, Docker, Heroku, and performance optimization. I love exploring new technology stacks and have recently developed an interest in mobile app development using Flutter. My skills in test-driven development and fixing security vulnerabilities have helped me deliver high-quality, reliable code. I am also currently learning about machine learning and its applications in real-world problem-solving. I bring a unique combination of technical expertise, creative problem-solving, and a passion for learning to any team. I am committed to delivering elegant and efficient software solutions and excited to contribute to an innovative and dynamic team that shares this vision.
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

