Sign In Anywhere with Devise – Ruby on Rails

The Devise gem ships with a default configuration that allows you to sign in on a specific route. This post address the idea of changing that guideline to allow a user to sign in anywhere.

Initial Setup

For the purposes of this demo, I used a Ruby on Rails application template I made called kickoff_tailwind. It leverages a few bells and whistles and ultimately saves me time creating and configuring Rails apps. Configuring Devise is one of those time savers that my application template takes care of for me. I also extend the User model to include name, username, and admin attributes. These don’t come by default with Devise.

All this is to say you’re welcome to use my template or roll a new Rails app from scratch. In the video, you’ll see me reference my template specifically.

Extending Devise logic

The easiest way to allow your login form to appear elsewhere in a given Ruby on Rails application is to include some methods that Devise depends on when rendering its forms. If you installed the devise views as I have you can see inside app/views/devise/sessions there is a template for rendering the login form specifically.

I’ll copy this and paste it into app/views/shared/_login.html.erb. This is a new folder and file I created which can easily be rendered anywhere in our app. To promote reusability I made it a partial in a new shared folder.

Rendering the template on localhost:3000 now results in an error. Devise expects some variables that aren’t available. We can approach adding these methods/variables in a number of ways but the easiest is to add it as helper logic in app/helpers/application_helper.rb. That way we have access to these virtually anywhere in the application.

# app/helpers/application_helper.rb

module ApplicationHelper
  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def resource_class
    User
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end
end

With the methods above-defined you should be able to reload your root path and see the login form. I go into greater detail about what’s happening and how to conditionally render the login form in the video. This concept makes logging in a breeze and ultimately doesn’t force you to use the Devise gem defaults. Pretty cool stuff!

The Series So Far

Shameless plug time

I have a new course called Hello Rails. Hello Rails is a modern course designed to help you start using and understanding Ruby on Rails fast. If you’re a novice when it comes to Ruby or Ruby on Rails I invite you to check out the site. The course will be much like these builds but a super more in-depth version with more realistic goals and deliverables. Download your copy today!!

Follow @hello_rails and myself @justalever on Twitter.