Rails 7 authentication with devise gem — add custom fields

Alfred Boateng
2 min readApr 30, 2023

--

Rails 7 Authorization Using Cancancan Gem

In this tutorial, we will learn to build a school-like app in Rails 7 and add authentication to it using the devise gem.

Let's follow the following steps

Add the devise gem to your gem file and run bundle install in terminal

gem "devise", github: "heartcombo/devise", branch: "main"

In your terminal

bundle install
rails generate devise:install

Follow the guide in the console to setup the home page, error messages, and views

Generate the user model. Remember to migrate after generating the user model

rails generate devise User

We want to add custom fields to the user model, including first name, last name, phone number date of birth, and gender. I also want to add email confirmation.

Update the user model, include confirmable, and add the required fields

Update controllers — Add strong parameters

Update Views to show authenticated user status

If you test the application now you will see that error messages are not showing up if the user provides invalid data. Let’s fix that

Create a new controller to handle devise errors

touch controllers/users/devise_controller.rb

Replace the content of `config/initializers/devise.rb`

You should be able to test your application with no error

I am available for job opportunities. PortfolioLinkedInGitHubEmail

--

--

Alfred Boateng

Full-Stack Web Developer, Javascript, React.js, Node.js, Ruby on Rails, Team player