[英]Rails routing: resources with only custom actions
我有一個NotificationsController
,其中我只有操作clear
。
我想通過執行 POST /notifications/clear 來訪問此操作
所以我在我的路由器里寫了這個:
resources :notifications, :only => [] do
collection do
post :clear
end
end
有沒有更清潔的方法來實現這一目標? 我想
scope :notifications do
post :clear
end
會這樣做,但我有一個missing controller
錯誤,因為 - 我認為 - 它尋找clear
控制器。
如果使用示波器,則應添加一個如下所示的控制器
scope :notifications, :controller => 'notifications' do
post 'clear'
end
或者只是使用命名空間
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
由於 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
最好只使用resources
塊only: []
。
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.