Adding login authentication to your Ruby on Rails application is a critical step to secure user data and ensure only authorized access. This guide walks you through implementing authentication in a Rails app using Devise, a popular authentication gem.
1. Set Up Your Rails Application
Install Rails
Ensure you have Rails installed. Run the following command to create a new Rails application:
bashCopy coderails new my_app
cd my_app
Add Devise Gem
In your Gemfile, add the following line to include the Devise gem:
rubyCopy codegem 'devise'
Run bundle install to install the gem.
2. Configure Devise
Install Devise
Run the generator to install Devise in your application:
bashCopy coderails generate devise:install
Follow the instructions provided by Devise to configure your environment. This includes setting up flash messages and default URLs for after-login redirection.
Generate a User Model
Use Devise to create a user model with authentication:
bashCopy coderails generate devise User
Run migrations to update your database:
bashCopy coderails db:migrate
3. Add Authentication to Views
Update Application Layout
Modify your app/views/layouts/application.html.erb file to include login/logout links. For example:
erbCopy code<% if user_signed_in? %>
<%= link_to 'Logout', destroy_user_session_path, method: :delete %>
<% else %>
<%= link_to 'Login', new_user_session_path %>
<% end %>
Restrict Access to Pages
Use before_action in controllers to restrict access to authenticated users. For instance:
rubyCopy codeclass PostsController < ApplicationController
before_action :authenticate_user!
end
4. Customize Devise
Add Fields to User Model
To include additional user fields, generate a migration:
bashCopy coderails generate migration AddFieldsToUsers name:string
rails db:migrate
Update the Devise strong parameters to permit these fields in app/controllers/application_controller.rb:
rubyCopy codebefore_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
end
5. Test Your Authentication
Create and Test Users
Start your Rails server and create test user accounts to ensure login, logout, and access restrictions work as expected.
Need Help Implementing Authentication?
Adding login authentication in Ruby on Rails can be challenging if you're new to the framework. If this guide feels overwhelming, I’m here to help! Contact me for expert assistance in building and securing your Rails application.
