【发布时间】:2011-02-20 05:37:48
【问题描述】:
Rails 定义了一堆具有命名路由的魔法,这些路由为您的路由提供帮助。有时,特别是对于嵌套路由,跟踪给定路由助手方法调用将获得的 URL 可能会有些混乱。是否可以使用 Ruby 控制台查看给定的辅助函数将生成什么链接?例如,给定一个像 post_path(post) 这样的命名助手,我想看看生成了什么 URL。
【问题讨论】:
标签: ruby-on-rails
Rails 定义了一堆具有命名路由的魔法,这些路由为您的路由提供帮助。有时,特别是对于嵌套路由,跟踪给定路由助手方法调用将获得的 URL 可能会有些混乱。是否可以使用 Ruby 控制台查看给定的辅助函数将生成什么链接?例如,给定一个像 post_path(post) 这样的命名助手,我想看看生成了什么 URL。
【问题讨论】:
标签: ruby-on-rails
您可以直接使用rake routes 向他们展示。
在 Rails 控制台中,您可以调用 app.post_path。这将适用于 Rails ~= 2.3 和 >= 3.1.0。
【讨论】:
app.get "/" 之类的方法将虚假请求粘贴到您的应用程序对象中,然后调用所需的方法 instance_eval,因为它们现在默认受到保护。比如:app.instance_eval{ post_path(post) }
app.teh_path 在 Rails 4.0 中仍然有效,可用于将引擎路径与主应用程序路径分开。
mount Spree::Core::Engine, :at => '/',然后您将通过引擎名称访问路径,例如 app.spree_core_engine.some_path。或者,如果“engine_name”被配置为不同的东西,比如in this code,那么你会做app.spree.some_path。
host 参数:app.article_url(my_article, host: 'mydomain.com')
你也可以
include Rails.application.routes.url_helpers
从控制台会话内部访问帮助程序:
url_for controller: :users, only_path: true
users_path
# => '/users'
或
Rails.application.routes.url_helpers.users_path
【讨论】:
Rails.application.routes.url_helpers.users_path?
在 Rails 控制台中,变量 app 包含一个会话对象,您可以在该对象上调用路径和 URL 助手作为实例方法。
app.users_path
【讨论】:
您可以随时在控制台中查看path_helpers 的输出。只需将助手与 app 一起使用
app.post_path(3)
#=> "/posts/3"
app.posts_path
#=> "/posts"
app.posts_url
#=> "http://www.example.com/posts"
【讨论】:
如果您的路线是命名空间的,请记住,例如:
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>"
【讨论】:
spree 的例子,你是从天而降的天使。
对于 Rails 5.2.4.1,我不得不
app.extend app._routes.named_routes.path_helpers_module
app.whatever_path
【讨论】: