3

Given a path such as

/foos/123

and a route

get '/foos/:id', as: 'foos'

How to get the ID using Rails routes (reverse) look up?

In this example, path.split('/').last would work, and a regex would be better. But how to use the Rails routes to do it?

This functionality was provided by Rails.application.routes.recognize_path but has been deprecated.

Note: This not part of a controller. Please do not answer about how to use routes within a controller.

Rails 6.

3
  • 1
    I don't think recognize_path was ever part of the public API and meant to be used. Maybe I'm wrong, but since this was deprecated I don't think there is other way than you just described with parsing raw URL/pah. Great question, up. Commented Dec 11, 2019 at 5:53
  • You have told us that the context is not a controller, what is it then? Commented Dec 11, 2019 at 11:50
  • @max - It is a model. Commented Dec 11, 2019 at 15:00

1 Answer 1

2

You can't. Routing is actually a lot more complicated than that.

The routes are not just a simple static set of regexes that match a string to a controller and action. You need an entire request object. You have to remember that constraints put things like headers, cookies and even middleware like Warden in the picture.

Rails.application.routes.recognize_path was depreciated since it completely failed at handling this complexity. It just gave a false sense of simplicity which is probably the worst thing software can do.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.