Hay! The system I'm working on has the following feature: after your disconnect, the next time you log in, you'll be redirected to the last page you've been.
That info is stored in the DB, as a string called first_place_after_login
, and Rails will take the user there.
The problem is that sometimes that route does not exist anymore.
Imagine your last page was 'activity/1', and that activity got deleted, when you log in, you're gonna see an error screen. The main issue with this, is that some users get confused why they hop right into an error when they just entered a 'normal' route (but got redirected to a invalid one).
So, before redirecting my user, I need to make sure that that route still exists, and it would be very bad to create a specific DB check for that (because there are dozens of possible routes that could not exist). So I wanted a way to send a request to my own route, and check the status it returns me.
I've tried this: Check if URL exists in Ruby, but the system is login-secured, so request returns as without permission.
Is there any practical way for me to validate my own routes?
You can use the same method that Rails uses to determine the controller and the other parameters from the route:
Imagine /activities/1
exists:
Rails.application.routes.recognize_path('/activities/1', method: :get)
#=> {:controller=>"activites", :action=>"show", :id=>"1"}
And if that routes doesn't exist anymore:
Rails.application.routes.recognize_path('/activities/1', method: :get)
#=> raises ActionController::RoutingError (No route matches "/activities/12")
With this, you can build a helper method like:
def redirect_to_last_page(url_from_session)
Rails.application.routes.recognize_path(url_from_session, method: :get)
redirect_to(url_from_session)
rescue ActionController::RoutingError
redirect_to root_path
end
Keep in mind that it doesn't cover cases like that the URL itself is valid like /activities/1
but the activities with the ID 1
was deleted from the database.