Quick Tip: Routes for a Non-Resourceful Rails Controller

Let’s say you have a few routes that are all related, but don’t really map to the usual resources. For example, a login/logout controller named SessionsController  doesn’t really fit the usual resourceful route model. One could use the usual routes HTTP verb syntax like this

Rails.application.routes.draw do
  get  'login',  to: 'sessions#index'
  post 'login',  to: 'sessions#login'
  post 'logout', to: 'sessions#logout'

However, there’s a nifty little helper that’s not in the routing guide but is in the API docs called controller which feels a bit cleaner.

Rails.application.routes.draw do
  controller :sessions do
    get  :login,  action: :index
    post :login,  action: :login
    post :logout, action: :logout

After running rake routes  or rails routes to see what routes we’ve got, we’ll see three routes.

login  GET  /login(.:format)  sessions#index
       POST /login(.:format)  sessions#login
logout POST /logout(.:format) sessions#logout

If there’s an even better way, let me know in the comments!


One Comment

A name is required.
An email is required.
Invalid URL

  1. Zuhaib Ali December 23, 2017

    The convention-over-configuration luxury is available here as well. You can skip having to specify the actions if they have the same name as the route.