Share This Article
Devise is a trendy authentication gem for Rails. In this article, I will show you how to implement Devise in Rails to establish user authentication in your application.
The first thing you need to do is install the Devise gem.
gem install devise
After the gem is installed, you need to run the devise generator.
rails generate devise:install
This will generate some configuration files and a migration.
The next thing you need to do is run the migration.
rails db:migrate
Now you need to generate the devise model.
rails generate devise User
This will generate a model and a migration.
The next thing you need to do is run the migration.
rails db:migrate
Now you need to add some routes.
Rails.application.routes.draw do
devise_for :users
end
Now you need to generate the devise views.
rails generate devise:views
Now you need to add the devise helper methods to your application layout.
<% if user_signed_in? %>
current user: <%= current_user.email %>
<%= link_to "Logout", destroy_user_session_path, method: :delete %>
<% else %>
<%= link_to "Login", new_user_session_path %>
<% end %>
You can now add some content to your home page.
<% if user_signed_in? %>
Welcome back, <%= current_user.email %>
<% else %>
Welcome to the site
<% end %>
You can now start the server & test the authentication.
rails server
You should now be able to register and log in users.
Restricting Access to Pages
If you want to restrict access to a page, you can use the authenticate_user!
method.
class PostsController < ApplicationController
before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
end
This will redirect users to the login page if they are not logged in.
You can also use the authenticate_user method to do something else if the user is not logged in.
class PostsController < ApplicationController
before_action :authenticate_user, only: [:new, :create, :edit, :update, :destroy]
end
You can use the cancan gem if you want to restrict access to a page based on the user’s role.
Summary
In this article, you’ve learned how to use the devise gem to establish user authentication in a Rails application.