23

我有一个NotificationsController,其中我只有动作clear

我想通过执行 POST /notifications/clear 来访问此操作

所以我在路由器里写了这个:

  resources :notifications, :only => [] do
    collection do
      post :clear
    end
  end

有没有更清洁的方法来实现这一目标?我想

  scope :notifications do
    post :clear
  end

会这样做,但我有一个missing controller错误,因为 - 我认为 - 它会寻找clear控制器。

4

3 回答 3

24

如果你使用范围,你应该添加一个控制器,看起来像

scope :notifications, :controller => 'notifications' do
  post 'clear'
end

或者只是使用命名空间

namespace :notifications do
  post 'clear'
end
于 2013-07-19T10:47:26.543 回答
1
post "notifications/clear" => "notifications#clear"
于 2013-07-19T10:29:44.413 回答
1
  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 helper 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

最好使用resourcesblock with 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
于 2021-12-28T06:28:55.390 回答