List of Controller Routes in Rails 3?
What I'm trying to do:
I create some controllers, for example:
- Home
- About
- Gallery
- Contact
Now I want to create a navigation au开发者_如何学Pythontomatically. So is there a way to programmatically fetch the list of controllers/actions to build this navigation?
I don't want to fix the navigation everytime I add a controller.
You can try something like this:
HomeController.action_methods.each do |action|
url_for(:action => action)
end
Here is a one liner that gives you all the controllers based on your routes file. I found I had a nil value, so I added the rescue, then rejected any of those rescued empty ones. The uniq drops any duplicates.
Rails.application.routes.routes.collect { |r| r.defaults[:controller] rescue '' }.reject! { |c| c.empty? }.uniq
Added a titlecase to make them more suitable for your navigation.
Rails.application.routes.routes.collect { |r| r.defaults[:controller].titlecase rescue '' }.reject! { |c| c.empty? }.uniq
This is one for only those in an admin namespace.
Rails.application.routes.routes.collect { |r| r.defaults[:controller].titlecase rescue '' }.reject { |c| c.empty? }.uniq.reject { |n| !n.include?('Admin/') }.map { |i| i.gsub('Admin/', '') }.sort
精彩评论