路由

  • 当需要为一个 RESTful 资源添加动作时(你真的需要吗?),应使用 member 路由和 collection 路由。
## 差
get 'subscriptions/:id/unsubscribe'
resources :subscriptions

## 好
resources :subscriptions do
  get 'unsubscribe', on: :member
end

## 差
get 'photos/search'
resources :photos

## 好
resources :photos do
  get 'search', on: :collection
end
  • 当需要定义多个 member/collection 路由时,应使用块结构。
resources :subscriptions do
  member do
    get 'unsubscribe'
    # 更多路由
  end
end

resources :photos do
  collection do
    get 'search'
    # 更多路由
  end
end
  • 使用嵌套路由(nested routes),它可以更有效地表现 ActiveRecord 模型之间的关系。
class Post < ActiveRecord::Base
  has_many :comments
end

class Comments < ActiveRecord::Base
  belongs_to :post
end

## routes.rb
resources :posts do
  resources :comments
end
  • 使用命名空间路由来归类相关的动作。
namespace :admin do
  # 将请求 /admin/products/* 交由 Admin::ProductsController 处理
  # (app/controllers/admin/products_controller.rb)
  resources :products
end
  • 不要使用旧式的控制器路由。这种路由会让控制器的所有动作都通过 GET 请求调用。
## 非常差
match ':controller(/:action(/:id(.:format)))'
  • 不要使用 match 来定义任何路由,除非确实需要将多种请求映射到某个动作,这时可以通过 via 选项来指定请求类型,如 [:get, :post, :patch, :put, :delete]。