1
\$\begingroup\$

In a Ruby on Rails application I want to have this routing:

  • for URL www.example.com/reports go to controller documents and action reports
  • for URL www.example.com/charts go to controller documents and action charts

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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 24, 2018 at 5:43
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

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.

answered May 28, 2018 at 13:25
\$\endgroup\$
3
  • \$\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\$ Commented May 28, 2018 at 13:37
  • \$\begingroup\$ @Coal_ sorry, first time I do code review and not answering on stackoverflow. \$\endgroup\$ Commented 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\$ Commented Jun 5, 2018 at 11:25
0
\$\begingroup\$

If you choose to use non-restful actions, you will have to define all of the custom actions.

answered May 26, 2018 at 13:09
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.