代码之家  ›  专栏  ›  技术社区  ›  Nilay Singh

Rails禁用编辑更新删除路由

  •  2
  • Nilay Singh  · 技术社区  · 6 年前

    我试图找到一种方法来禁用资源路由,比如编辑、销毁和更新。可以用这个答案来完成。 Disable Route 在这个答案中,我可以把这样的代码:

    resources :books, except: [:edit, :destroy]
    

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

             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 
                     ......
    

    我有近100条这样的路线,如果我必须一个接一个地改变这些方法,那将是一项艰巨的任务。是否有任何方法可以将这些路由分组到某个方法中,并拒绝所有资源路由的编辑、更新和销毁。

    1 回复  |  直到 6 年前
        1
  •  4
  •   Ovidiu Toma    6 年前

    我想你可以在你的 routes.rb 像这样的文件:

    scope except: [:edit, :destroy] do
      resources :users
    end
    

    将返回路线:

    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
    

    你可以看到 users#destroy users#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