How to Use Devise Gem

Contents
In this article, you will learn how to use devise gem.
Using devise gem
Devise is a popular Ruby gem that provides an easy way to implement authentication and authorization in Rails applications. We’ll cover the basic steps to use Devise in your Rails app.
Install the devise gem
Add Devise to your Gemfile and run bundle install:
gem 'devise'
Generate the devise configuration
Next, generate the Devise configuration by running:
rails generate devise:install
This command generates an initializer file at “config/initializers/devise.rb” and configures your application to use devise.
Generate the User model
Now that devise is installed and configured, we can generate the User model by running:
rails generate devise User
This command generates a migration file to create the users table, a model file for the User model, and a routes file for devise.
Run the migration
Now that the migration file has been generated, run the migration to create the users table:
rails db:migrate
Customize the User model
By default, devise provides a basic User model with a few fields like email and password. You can customize the User model by adding or removing fields as needed. To add a field, create a new migration and add the field to the users table:
rails generate migration add_field_to_users field:type
Add Authentication to other models
If you have other models that you want to authenticate with devise, you can add the devise method to the model and specify the desired modules:
class Admin < ApplicationRecord
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
end
Customize devise views
Devise provides default views for sign up, sign in, password reset, etc. You can customize these views by generating them with the following command:
rails generate devise:views
This command generates the views in the app/views/devise directory. You can then customize these views as needed.
Secure your app
With Devise installed, your application is now more secure. However, there are still a few things you can do to make it even more secure:
- Use SSL to encrypt traffic
- Add password complexity requirements
- Limit login attempts
- Use two-factor authentication