Rails用命名路由定义了一堆神奇的东西,它们为你的路由提供了帮助。有时候,特别是对于嵌套路由,跟踪给定路由助手方法调用的URL可能会让人有点困惑。是否可以使用Ruby控制台查看给定的helper函数将生成什么链接?例如,给定一个像post_path(post)这样的命名助手,我想看看生成了什么URL。


当前回答

对于Rails 5.2.4.1,我必须这么做

app.extend app._routes.named_routes.path_helpers_module
app.whatever_path

其他回答

在Rails控制台中,变量app保存了一个会话对象,您可以在该对象上调用path和URL helper作为实例方法。

app.users_path

你也可以

include Rails.application.routes.url_helpers

从控制台会话中访问helper:

url_for controller: :users, only_path: true
users_path
# => '/users'

or

Rails.application.routes.url_helpers.users_path

对于Rails 5.2.4.1,我必须这么做

app.extend app._routes.named_routes.path_helpers_module
app.whatever_path

您可以直接用rake路由显示它们。

在Rails控制台中,您可以调用app.post_path。这将在Rails ~= 2.3和>= 3.1.0中工作。

你总是可以在控制台中检查path_helpers的输出。只需要使用app的助手

app.post_path(3)
#=> "/posts/3"

app.posts_path
#=> "/posts"

app.posts_url
#=> "http://www.example.com/posts"