Dennis
Dennis

Reputation: 59577

Rails routes: namespace + resource + collection vs match

How does using a namespace + resource + collection compare to using a match.

For example, say I want to handle all HTTP methods for some endpoint.

namespace :webhooks do
  resources :some_service, only: :none do
    collection do
      get    :some_action
      post   :some_action
      put    :some_action
      patch  :some_action
      delete :some_action
    end
  end
end

# Compare to

match '/webhooks/some_service/some_action', to: 'webhooks/some_service#some_action', via: :all

Here are the associated routes according to rake routes:

                                 Prefix Verb     URI Pattern                                       Controller#Action

some_action_webhooks_some_service_index GET      /webhooks/some_service/some_action(.:format)      webhooks/some_service#some_action
                                        POST     /webhooks/some_service/some_action(.:format)      webhooks/some_service#some_action
                                        PUT      /webhooks/some_service/some_action(.:format)      webhooks/some_service#some_action
                                        PATCH    /webhooks/some_service/some_action(.:format)      webhooks/some_service#some_action
                                        DELETE   /webhooks/some_service/some_action(.:format)      webhooks/some_service#some_action
      webhooks_some_service_some_action          /webhooks/some_service/some_action(.:format)      webhooks/some_service#some_action

Besides line count, are there reasons why I should prefer one way over the other?

Upvotes: 1

Views: 974

Answers (1)

dre-hh
dre-hh

Reputation: 8044

In this case match is the best solution. The resources config should be used primary for defining restful routes (plus some exceptional other routes), which as the keyword already says implies of having some Resource as an endpoint. E.g you use Session#create instead of AuhtService.perfom_sing_in (having Session as the restful Resource instead of performing an rpc call to a service)

In your case you're not having any REST semantics in the routes at all, so match is just fine

Upvotes: 1

Related Questions