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.
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.
PrerequisitesThis 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)
- Close any files you may have open.
- Open the Finder and navigate to Class Files > yourname-Rails Class
- Open Terminal.
- Type
cdand a single space (do NOT press Return yet). - Drag the yourname-Rails Class folder from the Finder to the Terminal window and press ENTER.
- Run
rm -rf nuttyto delete your copy of the nutty site. - Run
Git clone https://bitbucket.org/Noble Desktop/nutty.Gitto copy the That Nutty Guy Git repository. - Type
cd nuttyto enter the new directory. - Type
Git checkout B2to bring the site up to the end of the previous exercise. - Run
bundleto install any necessary gems. - Run
yarn install—check-filesto install JavaScript dependencies.
Quick Setup Process
Clean Environment
Close files, navigate to Class Files folder, and delete existing nutty directory
Clone Repository
Use Git clone to download fresh copy of That Nutty Guy project repository
Checkout Branch
Switch to B2 branch to match the end state of previous exercises
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.
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.
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.
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.
Save the file, then close it.
We need to run the bundler to install the new gem. In Terminal, type:
bundleBundler will resolve dependencies and install the Devise gem along with any required dependencies. This process ensures version compatibility across your entire gem ecosystem.
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 rubyTerminal will return a process ID number that we need to terminate. Type
killfollowed by a space and then that number:kill #####Restart the Rails server by typing:
rails s -dThe
-dflag runs the server in daemon mode, allowing you to continue using the terminal while the server runs in the background.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.
Next, we'll run the Devise generator to create the necessary configuration files. In Terminal, type:
rails generate devise:installThis 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.
Generate the Customer model with Devise authentication by typing:
rails g devise CustomerThis 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.
Apply the migration to create the customers table in your database:
rails db:migrateRestart the server one more time to load the new model. Type:
pgrep rubyTerminal will return a process ID. Type
killfollowed by a space and then the number:kill #####Restart the Rails server:
rails s -d
Devise Installation Timeline
Add Gem to Gemfile
Include devise gem with descriptive comment
Run Bundle Install
Install gem and restart Rails server
Generate Devise Config
Run devise:install generator for initial setup
Create Customer Model
Generate and migrate Customer authentication model
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.
Launch a browser and navigate to: localhost:3000
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.
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.
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 beuser_signed_in?. Devise generates a complete set of helper methods for each authenticated model.Save the file.
Let's examine the available routes that Devise has generated for us. In Terminal, type:
rails routesThis 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.
The route we need is
new_customer_session, which renders the sign-in form. Return to application.html.erb in your code editor.Around line 37, locate this line of code:
<a href="cart.html">Sign In</a>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 %>For signed-in customers, we'll provide a sign-out option using the
destroy_customer_sessionroute. 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 %>Save the file.
Return to Terminal and examine the routes list again if needed.
Pay attention to the HTTP verbs in the
Verbcolumn—this is crucial for proper route implementation:- The verb for
new_customer_sessionisGET, which is Rails' default for link_to helpers, so no additional specification is needed. - The verb for
destroy_customer_sessionisDELETE, which is why we must explicitly specifymethod: :delete. This follows RESTful conventions where DELETE requests destroy resources (in this case, the user session).
- The verb for
Sign-in Implementation Checklist
Show different links based on customer_signed_in? status
Use new_customer_session_path for GET requests
Use destroy_customer_session_path with DELETE method
Use rails routes command to verify correct paths and HTTP verbs
HTTP Verbs for Authentication Routes
| Feature | Sign In | Sign Out |
|---|---|---|
| Route Helper | new_customer_session_path | destroy_customer_session_path |
| HTTP Verb | GET (default) | DELETE (specified) |
| Method Required | No | method: :delete |
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.
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
Select all the code (Cmd–A) and copy it (Cmd–C), then close the file.
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:
:alertfor error messages and:noticefor success messages. Devise automatically populates these flash types based on authentication outcomes.Save the file. Our authentication system is now complete and ready for testing.
Navigate to your browser and reload localhost:3000
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.
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.
Enter your email address and create a secure password. Devise enforces password strength requirements by default.
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.
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.
Click the Sign In link again to test the sign-in process.
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
Create New Account
Click Sign In, then Sign Up link to create account with email and password
Verify Success Messages
Confirm green success banner appears after successful signup
Test Sign Out
Click Sign Out link and verify logout confirmation message displays
Test Sign In
Use existing credentials to sign back in and verify authentication works