Single user setup for Devise

Monday January 16, 2017

If you want to have a user login for your Rails application, but you know that you will be the only user, there is an easy solution for the Devise gem that will prevent other users, or bots, from attempting to create new users for your app.

This is done by checking how many users your User model contains. Assuming you set up a user for yourself, as the only user, this will prevent anyone from getting to the new or create actions of the Devise RegistrationsController. Found the solution below in the Devise docs.

# config/routes.rb
devise_for :users, controllers: { registrations: "registrations"}

# registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController

  before_action :one_user_registered?, only: [:new, :create]


  def one_user_registered?
    if ((User.count == 1) & (user_signed_in?))
      redirect_to root_path
    elsif User.count == 1
      redirect_to new_user_session_path


If there is one user and the user is signed in, attempting to go to /users/sign_up will redirect to the root. Otherwise, it will redirect to the /users/sign_in page.


Written by Robin Hamill

Robin is an independent web application and ecommerce developer living in Toronto. He builds intuitive and functional web apps that engage users and solve problems. He's also excited about climbing rocks, travelling and learning all the things. 💎⛪️