Rails 禁用编辑更新删除路线

Nil*_*ngh 2 routes ruby-on-rails

我正在尝试找到一种方法来禁用资源路由,例如编辑销毁和更新。可以使用这个答案来完成。禁用路由在这个答案中我可以输入如下代码:

resources :books, except: [:edit, :destroy]
Run Code Online (Sandbox Code Playgroud)

它会起作用,但我有一个独特的问题,我创建了许多资源路由,我的路由文件如下所示:

         resources :expenditure_management2s do 
                            collection { post :import }
                            collection { get :dropdown }
                            collection { get :test }
                            end 
        resources :expenditure_management1s do 
                            collection { post :import }
                            collection { get :dropdown }
                            collection { get :test }
                            end 
        resources :expenditure_managements do 
                            collection { post :import }
                            collection { get :dropdown }
                            collection { get :test }
                            end 
                 ......
Run Code Online (Sandbox Code Playgroud)

我有差不多100条这样的路线,如果我必须一一改变这些方法,那将是一项艰巨的任务。有什么方法可以将这些路由分组为某种方法并拒绝编辑更新并销毁所有资源路由。

小智 5

我想你可以在你的routes.rb文件中使用一个范围,如下所示:

scope except: [:edit, :destroy] do
  resources :users
end
Run Code Online (Sandbox Code Playgroud)

将返回路线:

users     GET   /users(.:format)   users#index
          POST  /users(.:format)   users#create
new_user  GET   /users/new(.:format)   users#new
user      GET   /users/:id(.:format)   users#show
          PATCH /users/:id(.:format)   users#update
          PUT   /users/:id(.:format)   users#update
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,users#destroyusers#edit路线丢失了。

在你的情况下,它将是:

 scope except: [:edit, :destroy] do
    resources :expenditure_management2s do 
                        collection { post :import }
                        collection { get :dropdown }
                        collection { get :test }
                        end 
    resources :expenditure_management1s do 
                        collection { post :import }
                        collection { get :dropdown }
                        collection { get :test }
                        end 
    resources :expenditure_managements do 
                        collection { post :import }
                        collection { get :dropdown }
                        collection { get :test }
                        end 
 end
Run Code Online (Sandbox Code Playgroud)