在 Rails 中,如何查看所有的“路径"?和“网址"Rails 的路由添加的方法?(更新:使用 Rails 控制台) [英] In Rails, how to see all the "path" and "url" methods added by Rails's routing? (update: using Rails console)
问题描述
[更新:不使用 rake 路由
,只是为了更了解 Rails 控制台]
似乎在 Rails 3 的rails 控制台"内部,我们可以使用 controller
,但在 Rails 2.2 或 2.3 中,我们需要使用 @controller
>
而在 Rails 3 中,我们可以打印出 Rails 路由为脚手架添加的所有路由 foo
:
ruby-1.9.2-p0 >puts controller.public_methods.grep(/path|url/).grep(/foo/).sort.join("\n")edit_foo_pathedit_foo_urlfoo_pathfoo_urlfoos_pathfoos_urlnew_foo_pathnew_foo_url
但是在 Rails 2.3.8 上,它提供了一堆 formatted_foos_path
等,而在 Rails 2.2.2 中什么也没有.如何为 Rails 2.3.8 和 2.2.2 打印出来?
Rails 2.3.8 的详细信息:
ruby-1.8.7-p302 >puts @controller.public_methods.grep(/path|url/).grep(/foo/).sort.join("\n")formatted_edit_foo_pathformatted_edit_foo_urlformatted_foo_pathformatted_foo_urlformatted_foos_pathformatted_foos_urlformatted_new_foo_pathformatted_new_foo_url
Rails 3.x–6.x
Rails.application.routes.named_routes.helper_names
Rails 2.x
helpers = Rails.application.routes.named_routes.helpers
这将为您提供所有已创建的命名路由方法.然后你可以做 helpers.map(&:to_s)
,以及任何你想要获得 foo 版本的正则表达式
[update: by not using rake routes
, just to understand Rails console a little more]
It seems like inside of "rails console" for Rails 3, we can use controller
, but in Rails 2.2 or 2.3, we need to use @controller
And in Rails 3, we can print out all the routes added by Rails routing for a scaffold foo
:
ruby-1.9.2-p0 > puts controller.public_methods.grep(/path|url/).grep(/foo/).sort.join("\n")
edit_foo_path
edit_foo_url
foo_path
foo_url
foos_path
foos_url
new_foo_path
new_foo_url
but on Rails 2.3.8, it gives a bunch of formatted_foos_path
, etc, and gives nothing for Rails 2.2.2. How to make it print out for Rails 2.3.8 and 2.2.2?
Details for Rails 2.3.8:
ruby-1.8.7-p302 > puts @controller.public_methods.grep(/path|url/).grep(/foo/).sort.join("\n")
formatted_edit_foo_path
formatted_edit_foo_url
formatted_foo_path
formatted_foo_url
formatted_foos_path
formatted_foos_url
formatted_new_foo_path
formatted_new_foo_url
Rails 3.x–6.x
Rails.application.routes.named_routes.helper_names
Rails 2.x
helpers = Rails.application.routes.named_routes.helpers
This will get you all the named route methods that were created. Then you can do helpers.map(&:to_s)
, and whatever regex you want to get your foo versions
这篇关于在 Rails 中,如何查看所有的“路径"?和“网址"Rails 的路由添加的方法?(更新:使用 Rails 控制台)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!