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.
Any object that you want users to be able to access via URI and perform CRUD (or some subset thereof) operations on can be thought of as a resource. In the Rails sense, it is generally a database table which is represented by a model, and acted on through a controller.
In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as. map.resources :photos. creates seven different routes in your application: HTTP verb.
rake routes will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
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
post "notifications/clear" => "notifications#clear"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With