我如何清理这个嵌套的Rails路由

时间:2012-05-22 20:28:07

标签: ruby-on-rails ruby ruby-on-rails-3

我有这个

devise_for :users
 resources :sites do
  resources :users
  get 'companies/search'
 end
 root :to => "welcome#index"
end

,路线看起来像这样

       site_users GET    /sites/:site_id/users(.:format)            users#index
                  POST   /sites/:site_id/users(.:format)            users#create
    new_site_user GET    /sites/:site_id/users/new(.:format)        users#new
   edit_site_user GET    /sites/:site_id/users/:id/edit(.:format)   users#edit
        site_user GET    /sites/:site_id/users/:id(.:format)        users#show
                  PUT    /sites/:site_id/users/:id(.:format)        users#update
                  DELETE /sites/:site_id/users/:id(.:format)        users#destroy
 site_companies_search GET /sites/:site_id/companies/search(.:format)  sites/:site_id/companies#search
            sites GET    /sites(.:format)                           sites#index
                  POST   /sites(.:format)                           sites#create
         new_site GET    /sites/new(.:format)                       sites#new
        edit_site GET    /sites/:id/edit(.:format)                  sites#edit
             site GET    /sites/:id(.:format)                       sites#show
                  PUT    /sites/:id(.:format)                       sites#update
                  DELETE /sites/:id(.:format)                       sites#destroy
             root        /                                          welcome#index

但我想知道是否有办法让这样的路线

       site_users GET    /:site_id/users(.:format)            users#index
                  POST   /:site_id/users(.:format)            users#create
    new_site_user GET    /:site_id/users/new(.:format)        users#new
   edit_site_user GET    /:site_id/users/:id/edit(.:format)   users#edit
        site_user GET    /:site_id/users/:id(.:format)        users#show
                  PUT    /:site_id/users/:id(.:format)        users#update
                  DELETE /:site_id/users/:id(.:format)        users#destroy

如果没有网址中的/ sites,则网址来自

/sites/some_name/users 
/sites/some_name/users/new

/some_name/users 
/some_name/users/new

将尽可能清理网址

2 个答案:

答案 0 :(得分:2)

resources :sites do
  get 'companies/search'
end
scope ':site_id' do
  resources :users
end
root :to => "welcome#index"

答案 1 :(得分:1)

如果您希望除了资源加载机制(例如inherited_resources)之外能够使用此功能并在site处执行/ CRUD操作,您可以绘制路线,如:

resources :sites, :path => "" do
  get 'companies/search'

  resources :users
end

root :to => "welcome#index"