How to add username field to devise gem?

Answer is now outdated [ Valid for rails4 ]

I have done the same. Please follow these steps:

  1. rails generate migration add_username_to_users username:string:uniq

  2. rake db:migrate

  3. add attr_accessible :username

  4. in application_controller.rb:

    before_action :configure_permitted_parameters, if: :devise_controller?
    
    protected
    def configure_permitted_parameters
       devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me) }
       devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :username, :email, :password, :remember_me) }
       devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :password, :password_confirmation, :current_password) }
    end 
    
  5. in config/initializers if you want to replace email by usernname

    config.authentication_keys = [ :username ]
    config.case_insensitive_keys = [ :username ]  
    config.strip_whitespace_keys = [ :username ]
    
  6. update the views.

Note if attr_accessible :usernamegives error try attr_accessor :username


If you are using rails 4 then put below code in application controller

class ApplicationController < ActionController::Base
 before_action :configure_permitted_parameters, if: :devise_controller?

 protected

 def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_up) << :username
 end
end