Rails 路由在 REST 之后默认创建 7 个 CRUD 操作。
resources :users
但是,我有一个 confirm_destroy
操作,我几乎在每个资源中都使用它,因为我在确认页面上有很多逻辑;这不仅仅是一个简单的是/否警报对话框。
resources :users do
get :confirm_destroy, on: :member
end
有了 50 多个资源,为每个资源写出这些变得很乏味,因此我的路由文件实际上长了 3 倍。
有什么方法可以为 resources
block 添加一个 Action 到标准 7 中,这样
resources :users
会和
一样resources :users do
get :confirm_destroy, on: :member
end
我可以在 route 使用它作为标准操作,即:
resources :users, only: [:show, :confirm_destroy, :destroy]
resources :users, except: [:confirm_destroy]
最佳答案
虽然不像您喜欢的那样优雅,但 Rails 的方式是使用路由问题,正如@dbugger 所建议的那样。
例如:
concern :confirmable do
get 'confirm_destroy', on: :member
end
resources :users, :widgets, concerns: :confirmable
$ rails routes
Prefix Verb URI Pattern Controller#Action
confirm_destroy_user GET /users/:id/confirm_destroy(.:format) users#confirm_destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
confirm_destroy_widget GET /widgets/:id/confirm_destroy(.:format) widgets#confirm_destroy
widgets GET /widgets(.:format) widgets#index
POST /widgets(.:format) widgets#create
new_widget GET /widgets/new(.:format) widgets#new
edit_widget GET /widgets/:id/edit(.:format) widgets#edit
widget GET /widgets/:id(.:format) widgets#show
PATCH /widgets/:id(.:format) widgets#update
PUT /widgets/:id(.:format) widgets#update
DELETE /widgets/:id(.:format) widgets#destroy
关于ruby-on-rails - Rails 路由 : add a custom route to the standard list of actions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68621092/