In a Ruby on Rails application I want to have this routing:
- for URL www.example.com/reports go to controller
documents
and actionreports
- for URL www.example.com/charts go to controller
documents
and actioncharts
In the routes.rb file I currently have:
scope controller: :documents do
get 'reports' => :reports
get 'charts' => :charts
end
The code works as expected, but is there a way so I keep the code dry and don't repeat the action names?
2 Answers 2
You could do the following. (I assume you already have a resourceful route for your documents right?)
resources :documents do
collection do
get 'reports'
get 'charts'
end
end
To take advantage of the nested routing provided by rails (see the docs)
Which will generate the following urls:
Prefix Verb URI Pattern Controller#Action
reports_documents GET /documents/reports(.:format) documents#reports
charts_documents GET /documents/charts(.:format) documents#charts
If you don't have any resourceful route, you have to declare it like you already did. The only thing to do would be iterating over an array like this:
scope controller: :documents do
%w(reports charts).each do |action|
get action
end
end
But IMO this hurts the readability of the code, and is only necessary when dealing with a lot of routes.
-
\$\begingroup\$ Code dumps ('try this:') are not allowed as answers here. Please add what this does and why it is better than OPs solution. \$\endgroup\$Daniel– Daniel2018年05月28日 13:37:59 +00:00Commented May 28, 2018 at 13:37
-
\$\begingroup\$ @Coal_ sorry, first time I do code review and not answering on stackoverflow. \$\endgroup\$siegy22– siegy222018年05月28日 13:47:00 +00:00Commented May 28, 2018 at 13:47
-
\$\begingroup\$ Your example works. You're right about readability, but I was just wondering how to do it, as I tried but I was unable to make it work. \$\endgroup\$True Soft– True Soft2018年06月05日 11:25:17 +00:00Commented Jun 5, 2018 at 11:25
If you choose to use non-restful actions, you will have to define all of the custom actions.