组织铁路线的更好方法是什么?

时间:2012-12-20 20:18:44

标签: ruby-on-rails

我只是想知道是否有更好的方法来组织这些铁路线路。也许在一个团体?我不熟悉这样的最佳实践。

TestApp::Application.routes.draw do
  root :to => 'posts#index'
  resources :posts, :except => :destroy
  match '/posts/page/:page' => 'posts#page'
  match '/posts/delete/:id' => 'posts#delete'
  match '/posts/undelete/:id' => 'posts#undelete'
  match '/posts/hide/:id' => 'posts#hide'
  match '/posts/unhide/:id' => 'posts#unhide'
  match '/help' => 'help#index'
end

1 个答案:

答案 0 :(得分:2)

,您可以将它们分组到嵌套在collection的块中的resources :posts块中,如下所示

resources :posts, :except => :destroy do
  collection do
    match 'page/:page'   => 'posts#page'
    match 'delete/:id'   => 'posts#delete'
    match 'undelete/:id' => 'posts#undelete'
    match 'hide/:id'     => 'posts#hide'
    match 'unhide/:id'   => 'posts#unhide'
  end
end

但这些路线并不是非常RESTful。我可能会建议类似以下的内容

resources :posts, :except => :destroy do
  member do
    get    'page/:page' => 'posts#page'
    delete 'delete'     => 'posts#delete'
    put    'undelete'   => 'posts#undelete'
    put    'hide'       => 'posts#hide'
    put    'unhide'     => 'posts#unhide'
  end
end

这会创建更清晰的路由,同时仍然指向相同的控制器/操作。您必须修改您的应用程序以指向正确的路线,以支持这种更为可接受的行为。

              GET    /posts/:id/page/:page(.:format)   posts#page
  delete_post DELETE /posts/:id/delete(.:format)       posts#delete
undelete_post PUT    /posts/:id/undelete(.:format)     posts#undelete
    hide_post PUT    /posts/:id/hide(.:format)         posts#hide
  unhide_post PUT    /posts/:id/unhide(.:format)       posts#unhide
        posts GET    /posts(.:format)                  posts#index
              POST   /posts(.:format)                  posts#create
     new_post GET    /posts/new(.:format)              posts#new
    edit_post GET    /posts/:id/edit(.:format)         posts#edit
         post GET    /posts/:id(.:format)              posts#show
              PUT    /posts/:id(.:format)              posts#update