Adding additional field and validation to Devise view/model in Rails app

Viewed 26992

I generated the default devise views with:

rails generate devise:views

Then I added a username field to the views/devise/registrations/new.html.erb form.

Currently, only email and password validation occurs. How do I validate presence and uniqueness of the username field? Do I need to add something to the User model?

4 Answers

I used both the of the tutorials mentioned in the other answers, Railscast #210 and the Devise Wiki. However, so far as I could tell they do not explicitly say how to validate the presence and/or uniqueness of the username field.

If you added username with a simple migration -

rails generate migration addUsernameToUser username:string

Then devise doesn't do anything special with that field, so you need to add checks for validation and uniqueness yourself in the User model.

class User < ActiveRecord::Base
...
  validates_presence_of :username
  validates_uniqueness_of :username

However, If you look at the RailsCast #209 there is an example of the migration used to create the User model.

class DeviseCreateUsers < ActiveRecord::Migration  
  def self.up  
    create_table(:users) do |t|  
      t.database_authenticatable :null => false  
      # t.confirmable  
      t.recoverable  
      t.rememberable  
      t.trackable  
      # t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both  

      t.timestamps  
    end  

    add_index :users, :email,                :unique => true  
    # add_index :users, :confirmation_token,   :unique => true  
    add_index :users, :reset_password_token, :unique => true  
    # add_index :users, :unlock_token,         :unique => true  
  end  

  def self.down  
    drop_table :users  
  end  
end  

Notice here that the users email is defined as being unique. Perhaps if username was added using this same syntax then devise magic would take care of presence and uniqueness.

If anybody is wondering how to get the login to check for username if its blank or to make sure to users cannot have the same username. I spent quite a few hours trying to figure this out and in the ned I only had to add :

validates_uniqueness_of :username, case_sensitive: false
validates_presence_of :username

to your user.rb file in app/models/

Here are the docs... https://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

This now throws the errors I need. I feel like an idiot because I found uniquness_of first , then went back to and spent hours trying to figure out how to check for a blank field then found it is in the same documentation as the other...I am a noob.

Now onto figure out how to change the error messages since they are not in the devise.en.yml

Related