假设我有一个路由器助手,我想了解更多信息,例如 blogs_path,我如何在控制台中找到其背后的地图语句。
我尝试生成和识别,但出现无法识别的方法错误,即使在我确实需要“config/routes.rb”之后
在 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
谢谢,佐比!
在 Rails 3.2 应用程序的控制台中:
# include routing and URL helpers
include ActionDispatch::Routing
include Rails.application.routes.url_helpers
# use routes normally
users_path #=> "/users"
基本上(如果我正确理解你的问题)它归结为包括 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
与这个特定问题无关,但可能有助于以与
rails routes
命令从 bash 控制台执行此操作相同的方式查找路线:
Rails::Command.invoke "routes"
这将为您提供相同的输出,这可能对调试 rspec 测试中的控制器有用。
但是,这仍然是迄今为止最好的答案。