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?

\$\endgroup\$
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.

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

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.