ruby on rails的新手,尝试获取此url结构:
/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"
或者有更简洁的方法来实现这一目标吗?
答案 0 :(得分:1)
我想你想称之为rails generate controller About index staff contact
通过三项操作AboutController
,index
和staff
生成contact
。然后你想允许传入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]的值将是“brazil”。
答案 1 :(得分: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"}
所以这些都路由到同一个控制器(我相信你想要的),而你只有三个动作:staff
,index
和contact
。如果:country
值存在于网址中,则params[:country]
值将作为参数传入,并将作为{{1}}进行访问。
这是你想要做的吗?