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:
[crayon-5ba898efc52be370806903/] 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:
[crayon-5ba898efc52cd189771998/] Next, generate model ‘User’ using Devise
[crayon-5ba898efc52d3379683169/] 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
[crayon-5ba898efc52d8851175342/] 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.

Read Also:  Maven: Set up java.library.path

Lastly, update your tests for the new User models.

Leave a Reply

Your email address will not be published. Required fields are marked *