2010-10-23 23 views
1

對於每個物種,我有很多數據集。對於每個數據集,我有很多表型。數據集的名稱在一個物種中是主鍵。該物種也具有串主鍵(例如,Homo sapiens的Hs)。所以,我希望能夠指定一個表型如下:關於Rails 3中嵌套路由的困惑,特別是自動生成的路徑

/species/Hs/mcgary/1 

其中mcgary是表型集的名稱(塞)。

我明白,我可以通過將以下行中我的routes.rb文件中得到這樣的結果:

match "/species/:species_id/:dataset(/:id/:action)" => 'phenotypes' 
match "/species/:species_id/:dataset/:id" => 'phenotypes#show' 

表型是表型控制器。物種有一個控制器,但數據集不 - 它的功能是由物種和Phenotype的控制器處理的。)

不幸的是,這並不能保證路徑將起作用,例如edit_species_dataset_phenotype_path。我不太清楚如何在routes.rb中編寫該指令。一種可能性是有,除了比賽的指令,執行以下操作:

resources :species do 
    resources :dataset do 
    resources :phenotypes 
    end 
end 

和剛剛成立重定向。但這很尷尬。有什麼方法可以使用匹配符號來獲得路徑的工作?喜歡新的路線,但希望文件中有一些完整的例子。我也注意到,如果我做了類似edit_species_dataset_path(species,dataset)的東西,我可以得到/species/:species_id/:phenotype_set_id路由格式 - 但我不確定如何使用它:abbrev on Species,而不是每種類型都有。有沒有辦法告訴它默認使用該列,而不是ID?

非常感謝。 (是的,我知道這樣的嵌套路線得到很尷尬。我沒事這一點。)

回答

1

我發現了一個不完美的解決方案,這是對resources():path選項。

resources :species do 
    resources :datasets do 
    resources :phenotypes, :path => "" 
    end 
end 

這使我對我本來想的路線,和三個控制器而不是兩個,這是不理想的輕微變化 - 但重要的是,它的工作原理。

我的路徑現在形式爲/ species/Hs/datasets/mcgary/1(對於表型1)。我也不得不在ApplicationHelper寫一些幫手的方法。這些使得三重嵌套資源變得更容易一些。

def phenotype_path(phenotype, dataset=nil, species=nil) 
    dataset ||= phenotype.dataset 
    species ||= phenotype.species 
    File.join(phenotypes_path(dataset, species), phenotype.id.to_s) 
end 

def phenotypes_path(dataset, species=nil) 
    species ||= dataset.species 
    File.join(species_path(species.abbrev), "datasets", dataset.name) 
end 

def edit_phenotype_path(phenotype, dataset=nil, species=nil) 
    File.join(phenotype_path(phenotype,dataset,species), "edit") 
end 

def new_phenotype_path(dataset, species=nil) 
    File.join(phenotypes_path(dataset, species), "new") 
end 

alias :dataset_path :phenotypes_path 

def edit_dataset_path(dataset, species=nil) 
    File.join(dataset_path(dataset, species), "edit") 
end 

def dataset_path(dataset, species=nil) 
    species ||= dataset.species 
    File.join(species_path(species.abbrev), "datasets", dataset.name) 
end 

def datasets_path(species) 
    species_datasets_path(species.abbrev) 
end 

不幸的是,這些路徑有時似乎與自動生成的路徑衝突。我不確定哪個模塊支持這些路徑,因此很難重寫它們。

另一個問題是,我不能完全弄清楚如何做species_path(物種),並使用它的縮寫。相反,我必須做species_path(species.abbrev)。