Reputation: 22148
I have a NotificationsController
, in which I only have the action clear
.
I'd like to access this action by doing POST /notifications/clear
So I wrote this in my router:
resources :notifications, :only => [] do
collection do
post :clear
end
end
Is there a cleaner way to achieve this? I thought
scope :notifications do
post :clear
end
would do it, but I have a missing controller
error, because - I think - it looks for the clear
controller.
Upvotes: 26
Views: 17112
Reputation: 395
namespace :notifications do
put :clear
end
scope :notifications, controller: :notifications do
put :clear
end
resources :notifications, only: [] do
collection do
put :clear
end
end
rails routes:
notifications_clear PUT /notifications/clear(.:format) notifications#clear
clear PUT /notifications/clear(.:format) notifications#clear
clear_notifications PUT /notifications/clear(.:format) notifications#clear # I choose this
Because of the url helper clear_notifications_*
, I will choose the 3rd combination.
resources :users do
namespace :notifications do
put :clear
end
scope :notifications, controller: :notifications do
put :clear
end
resources :notifications, only: [] do
collection do
put :clear
end
end
end
rails routes:
user_notifications_clear PUT /users/:user_id/notifications/clear(.:format) notifications/users#clear
user_clear PUT /notifications/users/:user_id/clear(.:format) notifications#clear
clear_user_notifications PUT /users/:user_id/notifications/clear(.:format) notifications#clear
Still better to use resources
block with only: []
.
P.S. I think it makes more sense by namespacing the notifications controller under users:
resources :users, module: :users do
resources :notifications, only: [] do
collection do
put :clear
end
end
end
clear_user_notifications PUT /users/:user_id/notifications/clear(.:format) users/notifications#clear
Upvotes: 3
Reputation: 8220
If you are using scope, you should add a controller looks like
scope :notifications, :controller => 'notifications' do
post 'clear'
end
Or just use namespace
namespace :notifications do
post 'clear'
end
Upvotes: 27