Ruby-on-rails Rails:从控制台检查路径助手的输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2846247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:40:46  来源:igfitidea点击:

Rails: Check output of path helper from console

ruby-on-rails

提问by Derek Thurn

Rails defines a bunch of magic with named routes that make helpers for your routes. Sometimes, especially with nested routes, it can get a little confusing to keep track of what URL you'll get for a given route helper method call. Is it possible to, using the Ruby console, see what link a given helper function will generate? For example, given a named helper like post_path(post) I want to see what URL is generated.

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

回答by Chubas

You can show them with rake routesdirectly.

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

In a Rails console, you can call app.post_path. This will work in Rails ~= 2.3 and >= 3.1.0.

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

回答by aghull

you can also

你也可以

include Rails.application.routes.url_helpers

from inside a console sessions to access the helpers:

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

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

or

或者

Rails.application.routes.url_helpers.users_path

回答by user3622458

In the Rails console, the variable app holds a session object on which you can call path and URL helpers as instance methods.

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

app.users_path

回答by Deepak Mahakale

You can always check the output of path_helpersin console. Just use the helper with app

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

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

app.posts_path
#=> "/posts"

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

回答by Arup Rakshit

Remember if your route is name-spaced, Like:

请记住,如果您的路线是命名空间的,例如:

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

Then try :

然后尝试:

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

output

输出

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