Skip to main content
March 23, 2026Noble Desktop Publishing Team/9 min read

User Sign-In with the Devise Gem

Master User Authentication with Rails Devise Gem

What You'll Build

User Authentication System

Implement secure sign-in and sign-out functionality using the industry-standard Devise gem for Rails applications.

Flash Message Display

Create user feedback system to display success messages, error alerts, and status updates across page transitions.

Dynamic Navigation

Build conditional navigation that shows different options based on user authentication status.

Topics Covered in This Ruby on Rails Tutorial:

Installing the Devise Gem, Alerts, and User Authentication Systems

Exercise Overview

This exercise completes the foundational authentication setup for the That Nutty Guy site—a critical component of modern web applications. In the previous Rails 1 class exercise, we introduced the Devise gem configuration for user authentication. Now we'll implement a robust authentication system that will serve multiple areas of the site, establishing the security layer that professional Rails applications require.

User authentication isn't just about login forms—it's about creating secure, scalable user experiences. The Devise gem remains the gold standard for Rails authentication in 2026, powering millions of applications with its battle-tested security features and extensive customization options.

  1. If you completed the previous exercises (B1–B2), you can skip the following sidebar. We strongly recommend finishing those exercises before proceeding, as they establish the foundational structure we'll build upon. If you haven't completed them, follow the setup instructions in the sidebar below.

    Prerequisites

    This exercise assumes completion of previous Rails exercises B1-B2. If you haven't completed them, follow the setup instructions in the next section to get caught up.

If You Did Not Do the Previous Exercises (B1-B2)

  1. Close any files you may have open.
  2. Open the Finder and navigate to Class Files > yourname-Rails Class
  3. Open Terminal.
  4. Type cd and a single space (do NOT press Return yet).
  5. Drag the yourname-Rails Class folder from the Finder to the Terminal window and press ENTER.
  6. Run rm -rf nutty to delete your copy of the nutty site.
  7. Run Git clone https://bitbucket.org/Noble Desktop/nutty.Git to copy the That Nutty Guy Git repository.
  8. Type cd nutty to enter the new directory.
  9. Type Git checkout B2 to bring the site up to the end of the previous exercise.
  10. Run bundle to install any necessary gems.
  11. Run yarn install—check-files to install JavaScript dependencies.

Quick Setup Process

1

Clean Environment

Close files, navigate to Class Files folder, and delete existing nutty directory

2

Clone Repository

Use Git clone to download fresh copy of That Nutty Guy project repository

3

Checkout Branch

Switch to B2 branch to match the end state of previous exercises

4

Install Dependencies

Run bundle and yarn install to set up all required gems and JavaScript packages

Adding the Devise Gem

Now we'll install and configure the Devise gem, which provides a complete authentication solution with features like password encryption, session management, and user registration flows. Devise abstracts away the complexity of secure authentication while maintaining the flexibility that professional applications demand.

  1. For this exercise, we'll continue working with the nutty folder located in Desktop > Class Files > yourname-Rails Class > nutty

    If you haven't already done so, open the nutty folder in your code editor. Modern editors like Sublime Text, VS Code, or RubyMine make project navigation significantly more efficient when you open the entire project folder.

  2. In your code editor, open nutty > Gemfile

    The Gemfile is the dependency manifest for your Rails application—think of it as the blueprint that tells Bundler exactly which gems and versions your application needs to function properly.

  3. Add the following code at the bottom of the file as shown in bold:

    # Use bcrypt
    # Gem 'bcrypt', Group: [:development, :test]
    
    # Use Devise gem for user authentication
    gem 'devise'

    Professional Tip: Always document your gem additions with clear comments. This practice becomes invaluable when working on teams or returning to projects months later. Future developers (including yourself) will appreciate understanding why specific gems were added.

  4. Save the file, then close it.

  5. We need to run the bundler to install the new gem. In Terminal, type:

    bundle

    Bundler will resolve dependencies and install the Devise gem along with any required dependencies. This process ensures version compatibility across your entire gem ecosystem.

  6. Whenever we install a new gem that affects the Rails environment, we need to restart our Rails server to load the new code. Type:

    pgrep ruby
  7. Terminal will return a process ID number that we need to terminate. Type kill followed by a space and then that number:

    kill #####
  8. Restart the Rails server by typing:

    rails s -d

    The -d flag runs the server in daemon mode, allowing you to continue using the terminal while the server runs in the background.

  9. For comprehensive documentation on Devise installation and configuration options, refer to the official guide at GitHub.com/plataformatec/devise (scroll down to Getting started). The Devise documentation is exceptionally thorough and covers advanced configuration scenarios you'll encounter in production applications.

  10. Next, we'll run the Devise generator to create the necessary configuration files. In Terminal, type:

    rails generate devise:install

    This generator creates the Devise initializer file where you can configure authentication behavior, email settings, and security parameters. It also provides helpful setup reminders in the terminal output.

    Now we'll configure our Devise model. In this application, we're implementing a dual-authentication system: an AdminUser model for site administration and a Customer model for customer-facing authentication. This separation of concerns enhances security and provides cleaner role-based access control.

  11. Generate the Customer model with Devise authentication by typing:

    rails g devise Customer

    This creates both the Customer model file and a database migration with all necessary authentication fields, including encrypted password storage, session tokens, and password reset functionality.

  12. Apply the migration to create the customers table in your database:

    rails db:migrate
  13. Restart the server one more time to load the new model. Type:

    pgrep ruby
  14. Terminal will return a process ID. Type kill followed by a space and then the number:

    kill #####
  15. Restart the Rails server:

    rails s -d

Devise Installation Timeline

Step 1

Add Gem to Gemfile

Include devise gem with descriptive comment

Step 2

Run Bundle Install

Install gem and restart Rails server

Step 3

Generate Devise Config

Run devise:install generator for initial setup

Step 4

Create Customer Model

Generate and migrate Customer authentication model

Model Naming Strategy

This tutorial uses 'Customer' instead of 'User' to distinguish from the upcoming 'AdminUser' model. This separation provides better organization for sites with multiple user types.

Creating the Sign in Page

With Devise configured, we'll now implement the user interface elements that allow customers to sign in and out. This involves creating dynamic navigation that responds to authentication state—a fundamental pattern in modern web applications.

  1. Launch a browser and navigate to: localhost:3000

  2. Notice the Sign In link at the top right of the page. We'll now make this link functional and dynamic, displaying different options based on whether a user is authenticated.

  3. In your code editor, navigate to: nutty > app > views > layouts > application.html.erb

    This is your application's main layout template—the wrapper that surrounds all page content. Any changes here affect every page in your application, making it the ideal place for global navigation elements.

  4. Add the following bold code around the Sign In link (around line 36):

    <% if customer_signed_in? %>
       <a href="cart.html">Sign In</a>
    <% end %>

    Note: The customer_signed_in? helper method is automatically generated by Devise based on your model name. If you used a different model name like User, the method would be user_signed_in?. Devise generates a complete set of helper methods for each authenticated model.

  5. Save the file.

  6. Let's examine the available routes that Devise has generated for us. In Terminal, type:

    rails routes

    This command displays all available routes in your application. Devise automatically generates a comprehensive set of routes for authentication, including sign-in, sign-out, registration, and password reset functionality.

  7. The route we need is new_customer_session, which renders the sign-in form. Return to application.html.erb in your code editor.

  8. Around line 37, locate this line of code:

    <a href="cart.html">Sign In</a>
  9. Replace it with the following bold code to create proper authentication-aware navigation:

    <% if customer_signed_in? %>
    <% else %>
       <%= link_to 'Sign In', new_customer_session_path %>
    <% end %>
  10. For signed-in customers, we'll provide a sign-out option using the destroy_customer_session route. Add the following bold code:

    <% if customer_signed_in? %>
       <%= link_to 'Sign Out', destroy_customer_session_path, method: :delete %>
    <% else %>
       <%= link_to 'Sign In', new_customer_session_path %>
    <% end %>
  11. Save the file.

  12. Return to Terminal and examine the routes list again if needed.

  13. Pay attention to the HTTP verbs in the Verb column—this is crucial for proper route implementation:

    • The verb for new_customer_session is GET, which is Rails' default for link_to helpers, so no additional specification is needed.
    • The verb for destroy_customer_session is DELETE, which is why we must explicitly specify method: :delete. This follows RESTful conventions where DELETE requests destroy resources (in this case, the user session).

Sign-in Implementation Checklist

0/4

HTTP Verbs for Authentication Routes

FeatureSign InSign Out
Route Helpernew_customer_session_pathdestroy_customer_session_path
HTTP VerbGET (default)DELETE (specified)
Method RequiredNomethod: :delete
Recommended: Always check rails routes output to verify the correct HTTP verb for each authentication action.

Flash Alerts & User Logins

Flash messages are Rails' built-in system for displaying temporary messages to users—essential for providing feedback about authentication actions, form submissions, and other user interactions. These messages persist across a single redirect, making them perfect for confirmation messages like "Successfully signed in" or error notifications.

Professional applications rely heavily on flash messages to create intuitive user experiences. Without proper flash message implementation, users receive no feedback about their actions, leading to confusion and poor usability.

  1. We've prepared a flash message template to streamline this implementation. In your code editor, open: Desktop > Class Files > yourname-Rails Level 2 Class > snippets > flash.rb

  2. Select all the code (Cmd–A) and copy it (Cmd–C), then close the file.

  3. Return to application.html.erb and paste the code (Cmd–V) right above the main content around line 61:

    <div class="container">
       <div id="main" role="main">
    
          <% if flash[:alert] %>
             <div id="flash" class="alert"><%= flash[:alert] %></div>
          <% elsif flash[:notice] %>
             <div id="flash" class="notice"><%= flash[:notice] %></div>
          <% end %>
    
          <%= yield %>
    
       </div>
    </div>

    This code checks for two types of flash messages: :alert for error messages and :notice for success messages. Devise automatically populates these flash types based on authentication outcomes.

  4. Save the file. Our authentication system is now complete and ready for testing.

  5. Navigate to your browser and reload localhost:3000

  6. Click the Sign In link at the top right of the page.

    Devise has automatically generated a complete sign-in form with proper styling and security features, including CSRF protection and encrypted password handling.

  7. Since this is a new application, you'll need to create an account first. Below the Sign In button, click the Sign up link.

    Devise provides a complete user registration flow out of the box, including email validation and secure password requirements.

  8. Enter your email address and create a secure password. Devise enforces password strength requirements by default.

  9. Click the Sign Up button.

    Upon successful registration, you'll be redirected to the main page with a green flash message confirming your account creation. This immediate feedback reassures users that their action was successful.

  10. In the top right corner, you'll now see a Sign Out link instead of the Sign In link. Click it to test the sign-out functionality.

    The sign-out process will display an appropriate flash message and return you to the signed-out state, demonstrating the complete authentication cycle.

  11. Click the Sign In link again to test the sign-in process.

  12. Enter your email and password, then click the Sign In button. Excellent—your authentication system is fully functional!

    You now have a production-ready authentication system with secure password handling, session management, and user-friendly feedback messages. This foundation will support all the advanced features we'll build in subsequent exercises.

    This completes the authentication setup for the That Nutty Guy site. You now understand how professional Rails applications handle user authentication and have hands-on experience with the Devise gem's capabilities. You're ready to proceed to Exercise 8A: Getting Started with Active Admin, where we'll build the administrative interface for managing site content.

Flash Message Types

Alert Messages

Display error messages like incorrect username or password using flash[:alert] with alert CSS class.

Notice Messages

Show success confirmations like successful login or logout using flash[:notice] with notice CSS class.

Testing Your Authentication System

1

Create New Account

Click Sign In, then Sign Up link to create account with email and password

2

Verify Success Messages

Confirm green success banner appears after successful signup

3

Test Sign Out

Click Sign Out link and verify logout confirmation message displays

4

Test Sign In

Use existing credentials to sign back in and verify authentication works

Key Takeaways

1Devise gem provides comprehensive user authentication for Rails applications with minimal configuration required
2Always restart the Rails server after installing new gems to ensure proper loading and functionality
3Use descriptive model names like Customer instead of User when building applications with multiple authentication types
4HTTP verbs matter for authentication routes - GET for sign-in forms, DELETE for sign-out actions
5Flash messages provide essential user feedback for authentication actions and require proper layout integration
6The rails routes command is invaluable for verifying correct route helpers and HTTP methods
7Conditional navigation logic using signed_in? helpers creates dynamic user experiences based on authentication status
8Proper gem documentation and setup guides like Devise's GitHub repository provide authoritative implementation instructions

RELATED ARTICLES