简体   繁体   English

在Rails应用程序中,如何获取路径的路线?

[英]How do I get the route for a path, in a rails application?

Given a method and path, I want to ask Rails how that request would be routed, and i want to be able to do this from console, and/or from a rake task. 给定方法和路径,我想问一下Rails如何路由该请求,并且希望能够从控制台和/或rake任务中执行此操作。 I figure this should be straightforward - ActionDispatch does this for every request, and the route testing methods obviously also do it. 我认为这应该很简单-ActionDispatch针对每个请求执行此操作,而路由测试方法显然也可以执行此操作。

(Currently: Rails 3.0.x, but for the gem I'm writing I will need to be able to do this in Rails 3.0 through 4.1, at minimum, and possibly in older versions as well.) (当前:Rails 3.0.x,但是对于我正在编写的gem,我将需要至少能够在Rails 3.0到4.1以及较旧的版本中做到这一点。)

I've been trying a few things like this: 我一直在尝试这样的事情:

routes = ActionDispatch::Routing::RouteSet.new
routes.recognize_path('/my/path/23/edit')

or 要么

Rails.application.routes.recognize_path('/my/path/23/edit')

In both cases, I get back "RuntimeError: route set not finalized". 在这两种情况下,我都返回“ RuntimeError:路由集未完成”。

I'm diving through the ActionDispatch code working it out slowly, but if anyone knows the answer off the top of their head it would save me considerable time. 我正在仔细研究ActionDispatch代码,以逐步解决问题,但是如果有人知道答案,这将为我节省大量时间。 So, thank you! 所以谢谢!

The canonical answer is actually as given in my question: 规范答案实际上就是我的问题:

# GET request
Rails.application.routes.recognize_path('/some/path/63') 

# POST request
Rails.application.routes.recognize_path('/some/path', {:method => :post })

It looks like that wasn't working because I'd previously tried initializing RouteSet manually, which had interfered with the environment's ability to properly load the routes. 好像没有用,因为我之前曾尝试过手动初始化RouteSet,这干扰了环境正确加载路由的能力。 When I restarted the console session, the above commands worked fine. 当我重新启动控制台会话时,上述命令运行良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM