Dwight
Dwight

Reputation: 12450

Get current path name in Rails

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;

I simply want to retrieve the name of the current route on a given request.

Upvotes: 7

Views: 14203

Answers (4)

Jonathan
Jonathan

Reputation: 11494

I had to use request.original_fullpath (Rails 5.2)

Upvotes: 0

Shadow Debugger
Shadow Debugger

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

jjbohn
jjbohn

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

Alireza
Alireza

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

Related Questions