我有以下内容:
routes.rb
resources :splashes, only: [:index, :create, :destroy]
get '/splash', to: 'splashes#index'
>rake routes | grep splash
splashes GET /splashes(.:format) splashes#index
POST /splashes(.:format) splashes#create
splash DELETE /splashes/:id(.:format) splashes#destroy
GET /splash(.:format) splashes#index
但是,当我尝试使用splash_url
时,会生成http://localhost:3000/splashes/1
。
我试过
get '/splash', to: 'splashes#index', as: 'splash'
但它给了
rake routes | grep splash
耙子流产!
ArgumentError:无效的路由名称,已在使用中:'splash' 您可能使用:as
选项定义了两个具有相同名称的路由,或者您可能正在覆盖已由具有相同命名的资源定义的路由。对于后者,您可以限制使用resources
创建的路由,如下所述: http://guides.rubyonrails.org/routing.html#restricting-the-routes-created
我尝试使用单数resource
,但它不会生成#index
操作,并且您无法删除特定的启动行。
答案 0 :(得分:1)
只需在资源声明之前放置您的单一路线获取声明,
get '/splash', to: 'splashes#index'
resources :splashes, only: [:index, :create, :destroy]
现在,rake路由将给出以下结果,
splash GET /splash(.:format) splashes#index
splashes GET /splashes(.:format) splashes#index
POST /splashes(.:format) splashes#create
DELETE /splashes/:id(.:format) splashes#destroy
通过上述方法,删除和获取路由会根据定义序列被覆盖,因为它们都具有相同的命名助手 spash_path 。因此,我建议您将命名助手添加到自定义 get / spash 路由,如下所示,
resources :splashes, only: [:index, :create, :destroy]
get '/splash', to: 'splashes#index', as: 'splash_index'
因此,现在您将获得自定义获取路径的单独命名路径 splash_index 。还有另一个解决方案,
resources :splashes, only: [:index, :create, :destroy]
resources :splash, only: [:index], controller: :splashes
因此,您将为 / spash 路由获得一个不同的命名助手,
splashes GET /splashes(.:format) splashes#index
POST /splashes(.:format) splashes#create
splash DELETE /splashes/:id(.:format) splashes#destroy
splash_index GET /splash(.:format) splashes#index