2011-10-01 52 views
1

新建Ruby on Rails的,試圖讓這個URL結構:如何在Ruby on Rails中添加第三級導航?

/about 
/about/staff 
/about/contact 
/about/brazil 
/about/brazil/staff 
/about/brazil/contact 

當我這樣做:

rails generate controller about index 
rails generate controller about staff 
rails generate controller about contact 

設置我的路線:

get "about", :to => "about#index" 
get "about/staff", :to => "about#staff" 
get "about/contact", :to => "about#contact" 

,一切都很好,但是當我需要爲巴西辦公室的第三層做同樣的事情時,我很難過。

我應該怎麼做

rails generate controller about brazil_index 
rails generate controller about brazil_staff 
rails generate controller about brazil_contact 

get "about/brazil", :to => "about#brazil_index" 
get "about/brazil/staff", :to => "about#brazil_staff" 
get "about/brazil/contact", :to => "about#brazil_contact" 

還是有一個更清潔的方法來實現這個目標?

回答

1

我想你想調用這個rails generate controller About index staff contact

與三個動作indexstaffcontact產生AboutController。然後,你要允許在id參數傳遞作爲第二路徑元素:

然後在config/routes.rb

get "about/index" 
    get "about/staff" 
    get "about/contact" 
    get "about/:id/index" => 'about#index' 
    get "about/:id/staff" => 'about#staff' 
    get "about/:id/contact" => 'about#contact' 

當我檢查路線與rake routes我現在看到:

$ rake routes 
    about_index GET /about/index(.:format)  {:controller=>"about", :action=>"index"} 
    about_staff GET /about/staff(.:format)  {:controller=>"about", :action=>"staff"} 
about_contact GET /about/contact(.:format)  {:controller=>"about", :action=>"contact"} 
       GET /about/:id/index(.:format) {:controller=>"about", :action=>"index"} 
       GET /about/:id/staff(.:format) {:controller=>"about", :action=>"staff"} 
       GET /about/:id/contact(.:format) {:controller=>"about", :action=>"contact"} 

您現在可以要求http://localhost:3000/about/brazil/staff和params [:id]的值將是「巴西」。

+1

這很好,但我建議使用param name':country'而不是':id'像這樣:'get'about /:country/index「' - 這樣你就可以訪問國家值爲'params [:country]'而不是'params [:id]'。 –

+0

感謝你們倆!這就是我一直在尋找的 – chrisan

1

這樣做的一個很好的選擇是通過在/config/routes.rb文件中使用「命名空間」像這樣單獨的路由:

namespace :about do 
    match '/' => 'about#index' 
    match '/staff' => 'about#staff' 
    match '/contact' => 'about#contact' 
    match '/:country/staff' => 'about#staff' 
    match '/:country/contact' => 'about#contact' 
end 

如果你再運行rake routes,你可以看到,導致路由:

/about(.:format)     {:controller=>"about/about", :action=>"index"} 
/about/staff(.:format)   {:controller=>"about/about", :action=>"staff"} 
/about/contact(.:format)   {:controller=>"about/about", :action=>"contact"} 
/about/:country/staff(.:format) {:controller=>"about/about", :action=>"staff"} 
/about/:country/contact(.:format) {:controller=>"about/about", :action=>"contact"} 

因此,所有這些路線相同的控制器(我相信這是你想要的東西),你只有三個動作:staffindexcontact。如果:country值存在於url中並且將作爲params[:country]訪問,則該值將作爲參數傳入。

這是你正在嘗試做什麼?