【发布时间】:2011-02-16 05:03:05
【问题描述】:
假设我有一个路由器助手,我想了解更多信息,例如 blogs_path,我如何在控制台中找到它背后的地图语句。
我尝试生成和识别,但出现无法识别的方法错误,即使在我确实需要 'config/routes.rb' 之后也是如此
【问题讨论】:
-
找到答案here...
标签: ruby-on-rails routes
假设我有一个路由器助手,我想了解更多信息,例如 blogs_path,我如何在控制台中找到它背后的地图语句。
我尝试生成和识别,但出现无法识别的方法错误,即使在我确实需要 'config/routes.rb' 之后也是如此
【问题讨论】:
标签: ruby-on-rails routes
Zobie's Blog 有一个很好的示例总结,展示了如何手动检查 URL 到控制器/操作的映射以及相反的情况。例如,以
开头 r = Rails.application.routes
访问路由对象(Zobie 的页面,几年前,说使用ActionController::Routing::Routes,但现在不推荐使用Rails.application.routes)。然后您可以根据 URL 检查路由:
>> r.recognize_path "/station/index/42.html"
=> {:controller=>"station", :action=>"index", :format=>"html", :id=>"42"}
并查看为给定的控制器/动作/参数组合生成的 URL:
>> r.generate :controller => :station, :action=> :index, :id=>42
=> /station/index/42
谢谢,佐比!
【讨论】:
root_path 这样的命名路由?
Rails.application.routes.url_helpers.my_path_helper
r.recognize_path "/station/submit", method: "POST"
在 Rails 3.2 应用程序的控制台中:
# include routing and URL helpers
include ActionDispatch::Routing
include Rails.application.routes.url_helpers
# use routes normally
users_path #=> "/users"
【讨论】:
include ActionDispatch::Routing。
.pryrc 或 .irbrc 文件中的绝佳候选对象
基本上(如果我理解你的问题的话)归结为包括 UrlWriter 模块:
include ActionController::UrlWriter
root_path
=> "/"
或者您可以在控制台中的调用前添加应用程序,例如:
ruby-1.9.2-p136 :002 > app.root_path
=> "/"
(这是所有 Rails v. 3.0.3)
【讨论】:
从您的项目目录运行 routes 命令将显示您的路由:
rake routes
这是你的想法吗?
【讨论】:
如果您看到类似的错误
ActionController::RoutingError: No route matches
在它应该工作的地方,你可能正在使用一个 Rails gem 或引擎,它像 Spree 在它预先设置路线的地方做一些事情,你可能需要做一些其他事情才能在控制台中查看路线。
在 spree 的情况下,这是在路由文件中
Spree::Core::Engine.routes.prepend do
...
end
要像@mike-blythe 建议的那样工作,您可以在generate 或recognize_path 之前执行此操作。
r = Spree::Core::Engine.routes
【讨论】: