0
0
Ruby on Railsframework~5 mins

Devise gem overview in Ruby on Rails

Choose your learning style9 modes available
Introduction

Devise helps you add user login and registration features to your Rails app quickly and safely.

You want users to sign up and log in to your website.
You need to manage user passwords securely.
You want to add features like password reset or email confirmation.
You want to save time by using a ready-made authentication system.
You want to keep user sessions and handle logout easily.
Syntax
Ruby on Rails
gem 'devise'
bundle install
rails generate devise:install
rails generate devise User
rails db:migrate

First, add Devise to your Gemfile and install it with bundler.

Then generate Devise configuration and a User model with authentication features.

Examples
Add this line to your Gemfile to include Devise in your project.
Ruby on Rails
gem 'devise'
Run this command to set up Devise's initial configuration files.
Ruby on Rails
rails generate devise:install
This creates a User model with Devise modules for authentication.
Ruby on Rails
rails generate devise User
Apply database changes to add users table with Devise fields.
Ruby on Rails
rails db:migrate
Sample Program

This example shows how to add Devise to a Rails app, create a User model, and require login for all pages. It also shows how to display login/logout links in the layout.

Ruby on Rails
# Gemfile
source 'https://rubygems.org'
gem 'rails', '~> 7.0'
gem 'devise'

# After running bundle install

# Terminal commands:
# rails generate devise:install
# rails generate devise User
# rails db:migrate

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :authenticate_user!
end

# app/views/layouts/application.html.erb
<% if user_signed_in? %>
  <p>Welcome, <%= current_user.email %>!</p>
  <%= link_to 'Logout', destroy_user_session_path, method: :delete %>
<% else %>
  <%= link_to 'Login', new_user_session_path %> |
  <%= link_to 'Sign up', new_user_registration_path %>
<% end %>
OutputSuccess
Important Notes

Devise handles many security details for you, like password encryption.

You can customize which features (modules) Devise uses, like confirmable or lockable.

Remember to add before_action :authenticate_user! to protect pages.

Summary

Devise is a ready-made tool to add user login and registration to Rails apps.

It saves time and improves security by handling common authentication tasks.

Use Devise commands to set up and customize user authentication easily.