Rails: Replace a hand made authentication system with Devise

Yesterday I decided to replace a hand made authentication system with Devise:

1. What was the situation:
I had a Rails app used SQL database and already had a hand made authentication system with the scaffold User and all the helper methods, the routing configuration … I wanted to replace it with Devise in order to be able to use all the features provided by it.

2. What to do:
First of all, I wanted the generator of Devise to create a scaffold User while my app already had a model named User. Therefore, the first thing I needed to do is to remove the User scaffold:

rails destroy scaffold User

This is the opposite of rails generate scaffold User. In other words, it removed everything rails generate created (model, view, controller, assets, helpers, database migration file). Note: I backed-up the app/models/user.rb, to keep all the business logic of User with other models.

Next, clean up everything related to the old User model:
First, go through all migration files and remove the files that make changes to the old User database table.
Second, remove the User table in your database. I myself removed the entire development database so I could start it from fresh.

Third, remove the routing of old User in config/routes.rb.Next, add the ‘devise’ into Gemfile and install it. Then, install Devise into Rails:

rails generate devise:install

Next, generate model ‘User’ using Devise

rails generate devise User

Check the db/schema.rb file to see the part that defined the creation of User table matched with the data migration file.

Now you are ready to run

rake db:setup

to regenerate the development database. Next, if you defined some relations of the User model with other models in the backed-up app/models/user.rb file (such as belongs_to, has_many, validates …etc), copy/paste them to the new app/models/user.rb to maintain its business logic. The next part is mainly fixing errors that came up while using the new Authentication, including changing the Controller and View.

Lastly, update your tests for the new User models.

Aly Chiman

Aly Chiman is a Blogger & Reporter at AlyChiTech.com which covers a wide variety of topics from local news from digital world fashion and beauty . AlyChiTech covers the top notch content from the around the world covering a wide variety of topics. Aly is currently studying BS Mass Communication at University.