2017-09-14 23 views
0

我有以下幾點:如何爲包含助手的資源創建單一的GET路徑?

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
rake aborted!
ArgumentError: Invalid route name, already in use: 'splash' You may have defined two routes with the same name using the :as option, or you may be overriding a route already defined by a resource with the same naming. For the latter, you can restrict the routes created with resources as explained here: http://guides.rubyonrails.org/routing.html#restricting-the-routes-created

我試圖用奇異resource,但它不產生#index動作,你不能刪除特定飛濺行。

+0

嘗試改變'資源:飛濺,只有:[:指數, :create,:destroy]'to'resources:splashes,only:[:create,:destroy]' – Pavan

+0

首先,我沒有理解使用* singular資源* **資源集合** – Pavan

+0

@Pavan第1條評論:這並沒有爲GET路徑創建一個'* _url'助手。第2條評論:這是一個_splash_頁面,一個_landing page_。飛濺對人類或營銷者來說沒有意義,但這就是表格和控制器的命名方式。這是爲了領導一代。沒有記錄將被顯示。 – Chloe

回答

1

只需將您的奇異路徑資源之前得到聲明聲明,

get '/splash', to: 'splashes#index' 
resources :splashes, only: [:index, :create, :destroy] 

現在,耙擊潰會給你下面的結果,

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。所以,我建議你到名爲助手添加到自定義獲得/ 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 
+0

哇,確實有效,但現在DELETE鏈接不起作用。 'link_to'Delete',splash_path(lead),method :: delete'產生'http:// localhost:3000/splash.1'。 – Chloe

+0

是的,我看到路由刪除和獲取基於定義順序被覆蓋,因爲它們都具有相同的命名助手spash_path。所以,我建議你爲「get/spash」定義一個命名路線,並使用該助手來獲得預期的o/p。我只是更新了答案。 – Mohanraj

+0

謝謝!我喜歡第二種方式,但使用第一種方式,因爲它更接近我的。 – Chloe

相關問題