Reputation: 12450
I would like to be able to get the name of the current route in a request in Ruby on Rails. I've found ways I can access the controller and action of the request, but I would like to access a string or symbol of the name.
For example, if I have a users
resource;
users_path
edit_users_path
I simply want to retrieve the name of the current route on a given request.
Upvotes: 7
Views: 14203
Reputation: 1
You can use the current_page?
method to achieve this.
current_page?(user_path(@user))
current_page?(edit_user_path(@user))
Here's a link: current_page? method
Upvotes: -1
Reputation: 209
The following code will give it to you.
Rails.application.routes.recognize_path(request.request_uri)
Note that there are a couple of exceptions that can get thrown in ActionDispatch::Routing::RouteSet
(which is what is returned from Rails.application.routes
) so be careful about those. You can find the implementation of the method here.
Upvotes: 2
Reputation: 2691
You can use the following methods to get the current url in your action but none of them will give you the name of the route like users_path
request.original_url # => www.mysite.com/users/1
request.request_uri # = > /users/1
Upvotes: 2