Ruby-on-rails 在 Rails 中,如何查看 Rails 的路由添加的所有“path”和“url”方法?(更新:使用 Rails 控制台)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5345757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:42:03  来源:igfitidea点击:

In Rails, how to see all the "path" and "url" methods added by Rails's routing? (update: using Rails console)

ruby-on-railsruby-on-rails-3

提问by nonopolarity

[update: by not using rake routes, just to understand Rails console a little more]

[更新:不使用rake routes,只是为了多了解 Rails 控制台]

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

似乎在 Rails 3 的“rails 控制台”内部,我们可以使用controller,但在 Rails 2.2 或 2.3 中,我们需要使用@controller

And in Rails 3, we can print out all the routes added by Rails routing for a scaffold foo:

而在 Rails 3 中,我们可以打印出所有由 Rails 路由添加到脚手架的路由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?

但是在 Rails 2.3.8 上,它给出了一堆formatted_foos_path,等等,而在 Rails 2.2.2 中什么也没有。如何为 Rails 2.3.8 和 2.2.2 打印出来?



Details for Rails 2.3.8:

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

回答by nzifnab

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

这将为您提供所有已创建的命名路由方法。然后你可以做helpers.map(&:to_s),以及你想要得到你的 foo 版本的任何正则表达式

回答by metronom72

Well in Rails 4, I use rake routes. Is it that you need?

在 Rails 4 中,我使用rake routes. 是你需要的吗?

回答by Joe Jansen

or load up localhost_path/rails/info/routesin your browser.

localhost_path/rails/info/routes在浏览器中加载。