This tutorial aims to guide you on how to set up user authentication in your Rails application using Devise. User authentication is a critical component of most web applications and Devise makes it easy to build this functionality into your Rails projects.
By the end of this tutorial, you will have a Rails application with user authentication enabled. You will learn how to integrate Devise into your application, create user sign-up and sign-in functionality, and manage user sessions.
Familiarity with Ruby on Rails and basic understanding of MVC architecture is required. You should also have Ruby on Rails installed on your local machine.
First, you need to add the Devise gem to your Rails application. In your Gemfile, add the following line:
gem 'devise'
Then, run bundle install
to install the gem.
Devise works by generating a model (typically User
) that handles user authentication. Generate this model by running:
rails generate devise User
This command will create a User model and configure it with default Devise modules.
After generating the User model, you need to update your database schema to include the new model. Run this command:
rails db:migrate
Devise also generates routes for user sign-up, sign-in, and other related functions. You can see these routes by running rails routes
.
To protect certain resources from non-authenticated users, you can use the authenticate_user!
before_action in your controllers:
before_action :authenticate_user!
Devise creates all views needed for authentication but they are hidden in the gem. To customize these views, you can generate them with this command:
rails generate devise:views
After running this command, you'll find the sign-up form in app/views/devise/registrations/new.html.erb
.
In your application layout (app/views/layouts/application.html.erb
), you can add links for users to sign-in and sign-out:
<% if user_signed_in? %>
<%= link_to 'Sign out', destroy_user_session_path, method: :delete %>
<% else %>
<%= link_to 'Sign in', new_user_session_path %>
<% end %>
This code checks if a user is signed in. If so, it displays a 'Sign out' link. Otherwise, it displays a 'Sign in' link.
In this tutorial, you've learned how to add user authentication to a Rails application using Devise. You've learned how to install Devise, generate a User model, run migrations, and protect resources. You've also learned how to customize Devise views and manage user sessions.
For further learning, you could explore other Devise modules like Confirmable and Lockable. You could also look into how to customize the User model to include additional fields.
Remember, the key to mastering a new skill is practice!