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

时间:2010-05-17 01:45:00

标签: ruby-on-rails

Rails定义了一堆带有命名路由的魔法,为你的路线提供帮助。有时,特别是对于嵌套路由,跟踪给定路由助手方法调用所获得的URL会有点混乱。是否有可能使用Ruby控制台查看给定帮助函数将生成什么链接?例如,给定一个像post_path(post)这样的命名助手,我想看看生成了什么URL。

6 个答案:

答案 0 :(得分:387)

您可以直接使用rake routes显示它们。

在Rails控制台中,您可以拨打app.post_path。这将适用于Rails~ = 2.3和> = 3.1.0。

答案 1 :(得分:304)

你也可以

include Rails.application.routes.url_helpers

从控制台会话内部访问帮助程序:

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

答案 2 :(得分:20)

在Rails控制台中,变量app包含一个会话对象,您可以在其上调用路径和URL帮助程序作为实例方法。

app.users_path

答案 3 :(得分:10)

您始终可以在控制台中检查path_helpers的输出。只需使用app

的帮助程序即可
app.post_path(3)
#=> "/posts/3"

app.posts_path
#=> "/posts"

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

答案 4 :(得分:1)

请记住,如果您的路线是名称间隔的,请:

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>" 

答案 5 :(得分:0)

对于Rails 5.2.4.1,我不得不

app.extend app._routes.named_routes.path_helpers_module
app.whatever_path
相关问题