2012-04-24 81 views
1

我有2種型號:嵌套資源和漂亮的URL

  1. 體育
  2. 競爭

在我的routes.rb我通常會做

resources :sports, :only => [:index, :show] do 
    resources :competitions, , :only => [:index, :show] 
end 

這給我的網址像/sports/1/competitions/4

但我要的是:controller/:id,而是直接將:name的路徑,像這樣/soccer/euro2012

我可以這樣做,得到的第一部分:

match "/:sports_name" => "sports#show", :as => :sport 

而且在我的控制器:

def show 
    @sport = Sport.find_by_name(params[:sports_name]) 
end 

但就是這樣。我不知道如何獲得嵌套的資源,或者如果我正在做一些根本性的錯誤。

回答

2

讓我們首先要嵌套的資源,如果你真的需要它們,然後照顧漂亮網址:

# nested resources: 
resources :sports, :only => [:index, :show] do 
    resources :competitions, , :only => [:index, :show] 
end 

# pretty urls: 
match "/show/:sport_name/:competition_name" => "competitions#show" 

你還需要「/秀」第一,因爲否則這條線路也將路線隔日路線(如/ sports/new)至competitions#show。當然,您可以將其重命名爲最適合您的情況。

現在,您可以通過params[:sport_name]訪問該項運動,並通過competitions#show中的params[:competition_name]進行比賽。

如果你想軌爲您生成的路徑,一些代碼附加到路徑:

match "/show/:sport_name/:competition_name" => "competitions#show", :as => "some_name" 

,併產生這樣的路徑:

some_name_path("sport", "competition") 

這將導致類似「 /表演/體育/競爭」。