2016-04-26 76 views
0

我想將一個名爲index的資源路由添加到Rails 4應用程序中,但生成的路由並不如預期。但是,如果我使用其他名稱(例如show_index),它們是。爲了證明,我也有沒有路由的香草Rails應用程序開始:有沒有辦法創建一個名爲`index`的Rails資源路由?

$ rake routes 
You don't have any routes defined! 

我添加了下面到config/routes.rb

resources :items 

將會產生以下足智多謀Rails的路線:

Prefix Verb URI Pattern    Controller#Action 
    items GET /items(.:format)   items#index 
      POST /items(.:format)   items#create 
new_item GET /items/new(.:format)  items#new 
edit_item GET /items/:id/edit(.:format) items#edit 
    item GET /items/:id(.:format)  items#show 
      PATCH /items/:id(.:format)  items#update 
      PUT /items/:id(.:format)  items#update 
      DELETE /items/:id(.:format)  items#destroy 

該應用程序有一個show操作,如果參數散列包含,則該操作可以呈現所謂的(這索引是一個應用程序特定的東西,而不是集合項目或類似的東西)。

我添加自定義index路線調用show行動的附加參數:

resources :items do 
    get 'index' => 'items#show', with: 'index' 
    end 

這將產生一個新的路線,但它有item_id而不是預期的id(在列表edit_item上述比較) :

item_index GET /items/:item_id/index(.:format) items#show {:with=>"index"} 

Routing documentationexplains,要得到:id的方法是使用on: :member,這樣的路線將需要

get 'index' => 'items#show', with: 'index', on: :member 

,但不會產生預期的結果。它增加了預期的路線,但它竊取從默認show行動item方法前綴,而不是使用自己的index_item(再次,比較上面列表中edit_item):

item GET /items/:id/index(.:format) items#show {:with=>"index"} 
    GET /items/:id(.:format)  items#show 

然而,有我用比其他的東西index,如show_index,那麼它會按預期工作:

get 'show_index' => 'items#show', with: 'index', on: :member 

產生

show_index_item GET /items/:id/show_index(.:format) items#show {:with=>"index"} 

因此,當路線被稱爲index時,行爲有所不同。我期望這是因爲隱含的resources路線使用這個名字,儘管我不認爲他們以一種會發生衝突的方式使用它。它看起來像我應該能夠添加一個新的index路線,這將成爲index_item(類似於存在edit_item和現有的item_index相反)。

我知道我可以通過使用不同的名稱來解決問題,正如我所演示的。但index讀取比show_index好。

所以我的問題要求是否可以指定一個資源路由與index是關鍵:id? `

+0

嘗試'get'index'=>'items#show',其中:'index',on :: member,如:'item_index'' –

+0

Rails的一個重要概念是「Convention over Configuration」。您的計劃是將七個Rails默認操作中的一個用作路由名稱在該決定中,您使用的是配置而非慣例,這是Rails反模式。是否有可能使其工作?當然,但這不是您希望作爲您在Rails應用程序上工作的示例展示的代碼。 – Elvn

+0

但是這不會改變七軌的默認操作。它增加了另一個適合七種默認操作的動作。恰恰相反,該操作的邏輯名是'index',但它不會以任何方式影響默認操作。 – starfry

回答

1

設置特定URL中使用as關鍵字,所以你可以試試:在你的願望

get 'index' => 'items#show', with: 'index', on: :member, as: 'item_index' 

或一個過程的。

+0

使用'item_index'會產生以'item_index_item'爲前綴的方法,但使用'index'會給出'index_item'的預期結果。 – starfry

相關問題