[英]Rails routing: resources with only custom actions
I have a NotificationsController
, in which I only have the action clear
.我有一个NotificationsController
,其中我只有操作clear
。
I'd like to access this action by doing POST /notifications/clear我想通过执行 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.会这样做,但我有一个missing controller
错误,因为 - 我认为 - 它寻找clear
控制器。
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.由于 url 助手clear_notifications_*
,我将选择第三个组合。
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: []
.最好只使用resources
块only: []
。
PS I think it makes more sense by namespacing the notifications controller under users: PS我认为通过命名用户下的通知控制器更有意义:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.