title: Beginner's guide to the Devise gem. published: true description: A quick reference guide to using Rails most popular User Authentication Gem. This is implemented on a workout app I have since deprecated. tags: gems, devise, rails, ruby


Recently I've been working on a Rails app to track work-out progress.

As you read in the title, this post is about using the Devise Gem, and I'll be working through using it at it's simplest form, to create a resource that I wished I'd had when I first tried it out.

The Devise Gem is users for User Authentication, It creates sign-up and sign-in forms, it also can be used to create user accounts for privacy. (I'm sure it can do more things, but this is how I'm using it. )

So as with all other gems, you'll need to install in the usual way by adding to your Gemfile, gem 'Devise' Then run bundle install in your terminal. After you've done that, you'll need to run the generator. rails generate devise:install. That command installs an initializer that will print a lot of instructions, the only one we need to focus on right now is adding a default URL for the Devise Mailer. You can use the suggested one for the sake of this application.

Next, we need to create our Devise model, you can name it anything, (e.g. User, Admin, Member or Staff) depending on your purpose. I'll be using "User", thus I'll run in my terminal, rails generate devise user, following that up with rails db:migrate.

The first action you should take is to ensure that your Rails routes are configured for Devise, which is done by adding the following to your config/routes.rb file,

```ruby devise_for :stages root to: "stages#index"

"stages" can be replaced by whatever you name your controller, it's just what I needed to name my controller.

``` This will create all the necessary routes for authentication of your application, and then lead to the main index page.

In order to make your parts of your application unavailable to people without an account, go into their controllers and before your methods begin, add the following helper,

ruby before_action :authenticate_user! Something to be aware of, is to make sure that your helper matches your Devise model (User, Admin, etc.)

The three most important helpers for Devise are as follows,

```ruby user_signed_in?

I used this to show the user’s email address in the top Navigation bar, and depending on their status to show “Log In” or “Log Out” options.

user_session

Used to create the Log In occurrence, which remains until I’m logged out, in which case it destroys that session.

current_user

This is used here to display the User's email in the navigation bar.

<% if user_signed_in? %> <%= current_user.email %>