• 当需要为一个 RESTful 资源添加动作时(你真的需要吗?),应使用 member 路由和 collection 路由。

      1. # 差
      2. get 'subscriptions/:id/unsubscribe'
      3. resources :subscriptions
      4. # 好
      5. resources :subscriptions do
      6. get 'unsubscribe', on: :member
      7. end
      8. # 差
      9. get 'photos/search'
      10. resources :photos
      11. # 好
      12. resources :photos do
      13. get 'search', on: :collection
      14. end
    • 当需要定义多个 member/collection 路由时,应使用块结构。

      1. resources :subscriptions do
      2. member do
      3. get 'unsubscribe'
      4. # 更多路由
      5. end
      6. end
      7. resources :photos do
      8. collection do
      9. get 'search'
      10. # 更多路由
      11. end
      12. end
    • 使用嵌套路由(nested routes),它可以更有效地表现 ActiveRecord 模型之间的关系。

      1. class Post < ActiveRecord::Base
      2. has_many :comments
      3. end
      4. class Comments < ActiveRecord::Base
      5. belongs_to :post
      6. end
      7. # routes.rb
      8. resources :posts do
      9. resources :comments
      10. end
    • 使用命名空间路由来归类相关的动作。

      1. namespace :admin do
      2. # 将请求 /admin/products/* 交由 Admin::ProductsController 处理
      3. # (app/controllers/admin/products_controller.rb)
      4. resources :products
      5. end
    • 不要使用旧式的控制器路由。这种路由会让控制器的所有动作都通过 GET 请求调用。

      1. # 非常差
      2. match ':controller(/:action(/:id(.:format)))'
    • 不要使用 match 来定义任何路由,除非确实需要将多种请求映射到某个动作,这时可以通过 via 选项来指定请求类型,如 [:get, :post, :patch, :put, :delete]