Dive into this comprehensive tutorial on how to setup and configure the Devise gem for user authentication in Ruby on Rails, including topics such as user logins, alerts, and creating a Sign In page.
This exercise is excerpted from Noble Desktop’s past web development training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.
Topics covered in this Ruby on Rails tutorial:
Installing the Devise gem, Alerts, User logins
Exercise Overview
This is the final piece of setup for the That Nutty Guy site. In the last exercise of the Rails 1 class, we learned how to configure the Devise gem, which we use for user authentication in Rails. We’re going to need that in several places on this site.
-
If you completed the previous exercises, you can skip the following sidebar. We recommend you finish the previous exercises (B1–B2) before starting this one. If you haven’t finished them, do the following sidebar.
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
cd
and 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 nutty
to delete your copy of the nutty site. - Run
git clone https://bitbucket.org/noble-desktop/nutty.git
to copy the That Nutty Guy git repository. - Type
cd nutty
to enter the new directory. - Type
git checkout B2
to bring the site up to the end of the previous exercise. - Run
bundle
to install any necessary gems. - Run
yarn install --check-files
to install JavaScript dependencies.
Adding the Devise Gem
First, we need to get the Devise gem installed, configured, and ready to use.
-
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, we suggest opening the nutty folder in your code editor if it allows you to (like Sublime Text does).
In your code editor, open nutty > Gemfile
-
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'
NOTE: We always like to add a comment to explain the purpose of the gem so that anybody who looks at it later will know what it’s for.
Save the file, then close it.
-
We need to run the bundler, so in Terminal, type:
bundle
NOTE: Don’t forget to hit Return after every command in Terminal unless we specifically say not to. We won’t keep reminding you.
-
Whenever we install a new gem, we need to stop and restart our Rails server. Type:
pgrep ruby
-
Terminal will return a number for the process id we need to kill. Type
kill
followed by a space and then the number.kill #####
-
Restart the Rails server by typing:
rails s -d
In case you can’t remember all the steps for adding the Devise gem, there’s a handy guide you can refer to: github.com/plataformatec/devise (scroll down to Getting started).
-
Next we need to run the generator. In Terminal, type:
rails generate devise:install
The next thing we need to do is configure our Devise model. Usually the model would be called user but as you’ll see when we start building the admin interface for the site, we’re actually going to have two different authenticatible user models. One will be called admin user which will be able to administer our site. And just to keep them separate and to make our code work better, we’ll call our customer-facing user model customer.
-
Type:
rails g devise Customer
-
Apply the migration by typing:
rails db:migrate
-
We need to restart the server one more time. Type:
pgrep ruby
-
Terminal will return a number for the process id we need to kill. Type
kill
followed by a space and then the number.kill #####
-
Restart the Rails server by typing:
rails s -d
Creating the Sign In Page
Launch a browser and navigate to: localhost:3000
Notice the Sign In link at the top right of the page. Let’s create a Sign In page.
-
In your code editor, navigate to:
nutty > app > views > layouts > application.html.erbIf the user is signed out, we want to show a Sign In link. If the user is signed in, we want to show a Sign Out link.
-
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: In the first line,
customer
would be whatever your model name is. For example, if your model name is user, you would typeuser_signed_in?
Save the file.
-
Let’s figure out what route to link to. In Terminal, there’s an easy way of seeing a list of all the routes associated with our application. Type:
rails routes
The appropriate route for us right now is
new_customer_session
which will allow the customer to sign in. Return to application.html.erb in your code editor.-
Around line 37, highlight this line of code:
<a href="cart.html">Sign In</a>
-
Replace it as shown in bold to allow the customer to sign in:
<% if customer_signed_in? %> <% else %> <%= link_to 'Sign In', new_customer_session_path %> <% end %>
-
On the other hand, if the customer needs to sign out, we’ll use
destroy_customer_session
(which is listed in Terminal’s list of routes). Type:<% 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.
Go back to Terminal.
-
The HTTP Verb is very important. You can see it in the list of routes in Terminal under the
Verb
column. Take note of the following two verbs:- The verb for
new_customer_session
isGET
which is the default, so we didn’t need to specify that in the code we just typed. - The verb for
destroy_customer_session
isDELETE
, so that’s why we addedmethod: :delete
in the code we just typed.
- The verb for
Flash Alerts & User Logins
One more thing we need to do: we need to display the Flash, an important parameter in Rails that’s used to convey messages between one page and another. For example, it might say, “You entered the wrong user name” or “You’ve been logged in successfully!” In order for these messages to be displayed to site users, we need to add the Flash somewhere in our design.
To simplify things, we included a file you can copy from. In your code editor, open: Desktop > Class Files > yourname-Rails Level 2 Class > snippets > flash.rb
Select all (Cmd–A) the code and copy (Cmd–C) it, then close it.
-
Go back to application.html.erb and paste it (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>
Save the file. Now we’re ready to test the login!
Go to your browser and reload localhost:3000
Click the Sign In link at the top right of the page.
Cool, we’ve got a sign in page! Since we’re new, we need to create a new account. Below the red Sign In button, click the Sign up link.
Enter your email and create a password.
-
Click the Sign Up button.
That should take you to the main page where there is a green alert banner telling you that you’ve signed up.
-
In the top right corner, there’s a Sign Out link. Click it.
That should sign you out and alert you accordingly.
Click the Sign In link at the top right of the page.
-
Enter your email and password and sign in. Yay, it works!
Hopefully you found this to be a helpful guide as to where the foundational elements of this site came from. If you did these bonus exercises first, you are now ready to continue on with Exercise 8A: Getting Started with Active Admin.