Sergii Kushch
Sergii Kushch

Reputation: 311

How to get current url route pattern in rails?

Lets imagine, I have a route defined like the following:

constraints MyRouteConstraint.new do
  get ':param/:param1/:param2', to: 'controller#action'
end

How can I get the pattern ':param/:param1/:param2' in my controller? I know there is Rails.application.routes.recognize_path "/param/param1/param2" but it raises an error 'No Route matches'

update:

Rails.application.routes.router.recognize(request) do |route, matches, parameters|
  return route.path.spec.to_s if route.path.required_names.all? { |p| request.params.keys.include? p }
end.flatten.compact.first

Upvotes: 12

Views: 1915

Answers (2)

Jack
Jack

Reputation: 1451

Since rails 7.1 there is request.route_uri_pattern

See https://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-route_uri_pattern

Upvotes: 1

neo
neo

Reputation: 4116

Not too sure if this is what you're looking for, this is meant to be used in your views.

You can try request.fullpath

Returns the String full path including params of the last URL requested.

# get "/articles"
request.fullpath # => "/articles"

# get "/articles?page=2"
request.fullpath # => "/articles?page=2"

See docs here:

http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url

Upvotes: -1

Related Questions