Rails用命名路由定义了一堆神奇的东西,它们为你的路由提供了帮助。有时候,特别是对于嵌套路由,跟踪给定路由助手方法调用的URL可能会让人有点困惑。是否可以使用Ruby控制台查看给定的helper函数将生成什么链接?例如,给定一个像post_path(post)这样的命名助手,我想看看生成了什么URL。
你也可以
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
记住,如果你的路线是以名字间隔的,比如:
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
推荐文章
- 在Rails中使用user_id:integer vs user:references生成模型
- 如何测试参数是否存在在轨道
- 验证多个列的唯一性
- Rails:在where语句中使用大于/小于
- Rails:如何为Rails activerecord的模型中的属性创建默认值?
- 库未加载:libmysqlclient.16。在OS X 10.6上使用mysql2 gem运行'rails server'时出现dylib错误
- 如何确定一个数组是否包含另一个数组的所有元素
- Rails find_or_create_by多个属性?
- Rails ActiveRecord日期之间
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 对于PostgreSQL表来说,多大才算太大?
- Rails:如何在Rails 4中引用CSS中的图像
- 如何使用RSpec的should_raise与任何类型的异常?
- Rails -嵌套包括活动记录?