Rails:从控制台检查路径帮助器的输出

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

137512 次浏览

你可以直接用rake routes来显示它们。

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

你也可以

include Rails.application.routes.url_helpers

从控制台会话中访问helper:

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

Rails.application.routes.url_helpers.users_path

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

app.users_path

记住,如果你的路线是以名字间隔的,比如:

product GET  /products/:id(.:format)  spree/products#show

然后试试:

helper.link_to("test", app.spree.product_path(Spree::Product.first), method: :get)

输出

Spree::Product Load (0.4ms)  SELECT  "spree_products".* FROM "spree_products"  WHERE "spree_products"."deleted_at" IS NULL  ORDER BY "spree_products"."id" ASC LIMIT 1
=> "<a data-method=\"get\" href=\"/products/this-is-the-title\">test</a>"

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

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


app.posts_path
#=> "/posts"


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

对于Rails 5.2.4.1,我必须这么做

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