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' end
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 end end
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!
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.