3
votes

I have a subscriptions controller with routes that look like this:

get  'user/:user_id/subscription_requests' => 'subscriptions#index', as: :subscription_requests
post 'user/:user_id/subscribe'             => 'subscriptions#subscribe', as: :user_subscribe
post 'user/:user_id/unsubscribe'           => 'subscriptions#unsubscribe', as: :user_unsubscribe
post 'user/:user_id/request_subscription'  => 'subscriptions#request_subscription', as: :request_user_subscription
post 'user/:user_id/accept_subscription'   => 'subscriptions#accept', as: :accept_subscription_request
post 'user/:user_id/reject_subscription'   => 'subscriptions#reject', as: :reject_subscription_request

All of them except index are non-restful actions. How do you make this cleaner in the routes file using something like resources while keeping the user/:user_id/ in the path?

Update for clarity:

I'm trying to avoid listing the routes line by line and instead do something like what rails provides with the restful actions. Something like:

resources :subscription_requests, :only => [:subscribe, :unsubscribe, :reject, :accept, etc]

1
Create your own mapping function that writes routes given an array of symbols? Or just loop by hand in routes? - Dave Newton

1 Answers

7
votes

You can use the member function of routing.

resources :user, to: 'subscriptions', :only => [] do
  member do
    get 'subscription_requests'
    post 'subscribe'
    etc
  end
end

And this will produce routes such as:

subscription_requests_user GET    /user/:id/subscription_requests(.:format)        subscriptions#subscription_requests
subscribe_user POST   /user/:id/subscribe(.:format)                    subscriptions#subscribe

Docs: http://guides.rubyonrails.org/routing.html#adding-more-restful-actions