Search code examples
ruby-on-railsdevise

Devise authenticating with username instead of email


I'm new to Devise and have it working fine by using an email address as the authentication key. However, I have a use case which requires a username instead and I can't seem to get it working.

I've added a string column, "username" to the users table, changed the fields from :email to :username in the sign-in form, and have changed the authentication key in devise.rb to :username yet when I go to sign in I'm met with this prompt: "Please enter an email address".

What am I doing wrong?

**new.html.erb**

  <div><%= f.label :username %><br />
  <%= f.email_field :username %></div>

**User.rb**
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:username]

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username
  # attr_accessible :title, :body
end

**devise.rb**
 config.authentication_keys = [ :username ]

Solution

  • In your config/initializers/devise.rb uncomment config.authentication_keys = [ :email] and change it to config.authentication_keys = [ :username ]

    Update:
    Your form's incorrect.
    Change f.email_field to f.text_field