如何从URI中删除资源类型段?

时间:2011-06-10 14:38:24

标签: ruby-on-rails-3 rest resources routing

我的项目包含文件和文件夹,由FileFolder模型表示。该项目功能齐全,现在我正在寻找清理URI方案,同时保留我的命名路由。

我的路线包含一个简单的嵌套资源:

resources :folders do
  resources :files
end

目前,folder_file_path(@folder, @file)输出:

/folders/12/files/3

我已经覆盖了to_param以输出一个人类可读的slug,产生了

/folders/my-folder/files/my-file

我想更进一步,从URI中删除多余的foldersfiles段。如何修改嵌套的resources以便folder_file_path输出以下内容?

/my-folder/my-file

我想保持我的路线简单,使用嵌套的resources而不是移动到更长的自定义命名路线,这就是我目前实现的目的:

get ':folder_slug' => 'folders#show', :as => 'folder'
get ':folder_slug/edit => 'folders#edit', :as => 'edit_folder'
# ...
delete ':folder_slug' => 'folders#destroy', : as => 'folder'

get ':folder_slug/:file_slug' => 'files#show', :as => 'folder_file'
get ':folder_slug/:file_slug/edit' => 'files#edit', :as => 'edit_folder_file'
# ...
delete ':folder_slug/:file_slug' => 'files#delete', :as => 'folder_file'

1 个答案:

答案 0 :(得分:1)

像这样的东西

resources :folders, path: ''
resources :folders, path: '', only: [] do
  resources :files, path: ''    
end