简而言之
我想改变Rails资源路由的默认行为,将所有资源的create
路径移动到/resources/new
的POST,而不是/resources
。
设置
让我们假设已经指定了一个资源路由:
# routes.rb
resources :events
实际生成的路由如下:
$ rake routes
Prefix Verb URI Pattern Controller#Action
events GET /events(.:format) events#index
POST /events(.:format) events#create
new_event GET /events/new(.:format) events#new
edit_event GET /events/:id/edit(.:format) events#edit
event GET /events/:id(.:format) events#show
PATCH /events/:id(.:format) events#update
PUT /events/:id(.:format) events#update
DELETE /events/:id(.:format) events#destroy
请注意,create
操作由对/events
路径的POST触发。
现在,如果我想更改该路径,我可以按资源自行进行:
# routes.rb
# I've placed the routes in this order, and used `as: "new_event"`,
# to avoid generating an `events_new` path helper.
post 'events/new' => 'events#create', as: "new_event"
resources :events, except: [:create]
以下为生成的路由:
$ rake routes
Prefix Verb URI Pattern Controller#Action
new_event POST /events/new(.:format) events#create
events GET /events(.:format) events#index
GET /events/new(.:format) events#new
edit_event GET /events/:id/edit(.:format) events#edit
event GET /events/:id(.:format) events#show
PATCH /events/:id(.:format) events#update
PUT /events/:id(.:format) events#update
DELETE /events/:id(.:format) events#destroy
太好了!现在
create
操作由/events/new
路径的POST触发,而不是/events
路径。每个其他的路由/助手都与以前完全一样,包括对
/events/new
的GET和new_event
路径/url助手的支持。问题
是否有一种方法可以仅更改用于该特定操作的默认路径,而不必手动覆盖每个
create
操作?如果无法实现上述功能,则我可以使用哪些其他手段来更改一堆资源路由,以便将其创建操作移动到如上所示的
/new
?谢谢!
resources
调用中添加except: :create
。 - m_xcustom_resources
方法,它会自动执行您手动执行的操作,并在过程中调用原始的resources
方法。 - m_x