Devise Custom Controllers

There could be a number of reasons to create a custom controller that overrides or appends behavior to resource actions, mine is one you will not find in most guides.

First, if you are creating a custom controller I suggest reading all of the Configuring Controllers section at https://github.com/plataformatec/devise.

Default Devise views need customization if you want them to blend in with the rest of your application, it is unavoidable. What is avoidable is creating errors by not generating scoped views:

rails generate devise:views

With multiple Devise models it becomes necessary to scope:

rails generate devise:views users

My user model was not scoped so all its views lived in a devise folder. My admin model was scoped so all of its views lived in an admin folder. After adding a custom attribute to my user model my admin session threw an error for that custom attribute. This meant that my admin session was using the user session’s html… hmm.

Turns out all you need is to configure a parameter somewhere in your app like so:

config.scoped_views = true

But this did not work and I still do not know why, maybe my case was special but if we look at my routes we can see that the controller being used is named ‘devise/session’:

Rails naming convention tells us that the views for these admin actions will be found in the devise folder. Well this explains why I was getting the user form so I attempted to generate scoped views for user but this did not work.

After following the devise instructions linked earlier I created a controller and pointed my session routes to this new controller. Now the proper views are rendered and we can see that my new routes reflect this change:

Fairly soon my app will require custom controllers to create new user functionality but right now my app needed them in order to take advantage of Rails’s naming convention.