Routing
When you need to add more actions to a RESTful resource (do you really need them at all?) use
member
andcollection
routes.# bad get 'subscriptions/:id/unsubscribe' resources :subscriptions # good resources :subscriptions do get 'unsubscribe', on: :member end # bad get 'photos/search' resources :photos # good resources :photos do get 'search', on: :collection end
If you need to define multiple
member/collection
routes use the alternative block syntax.resources :subscriptions do member do get 'unsubscribe' # more routes end end resources :photos do collection do get 'search' # more routes end end
Use nested routes to express better the relationship between ActiveRecord models.
class Post < ActiveRecord::Base has_many :comments end class Comments < ActiveRecord::Base belongs_to :post end # routes.rb resources :posts do resources :comments end
If you need to nest routes more than 1 level deep then use the
shallow: true
option. This will save user from long urlsposts/1/comments/5/versions/7/edit
and you from long url helpersedit_post_comment_version
.resources :posts, shallow: true do resources :comments do resources :versions end end
Use namespaced routes to group related actions.
namespace :admin do # Directs /admin/products/* to Admin::ProductsController # (app/controllers/admin/products_controller.rb) resources :products end
Never use the legacy wild controller route. This route will make all actions in every controller accessible via GET requests.
# very bad match ':controller(/:action(/:id(.:format)))'
Don't use
match
to define any routes unless there is need to map multiple request types among[:get, :post, :patch, :put, :delete]
to a single action using:via
option.