簡體   English   中英

Rails 路由:只有自定義操作的資源

[英]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"
  1. 我嘗試了三種組合:
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_* ,我將選擇第三個組合。


  1. 此外,實際上我想將這些路由嵌套在資源中:
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

最好只使用resourcesonly: []


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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM