Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique usernames in Devise for Rails

I followed Devise's instructions for using usernames in addition to emails for logins. Works great except people can signup with duplicate usernames. If someone tries to signup with a duplicate email address, they are presented with this error message on the signup page:

1 error prohibited this user from being saved:

Email has already been taken

I want something very similar for usernames. How do I implement this?

like image 911
at. Avatar asked Oct 02 '12 07:10

at.


2 Answers

You should use uniqueness validator. Add following into user.rb:

validates_uniqueness_of :username

more about this validator

like image 170
Vadim Chumel Avatar answered Nov 12 '22 09:11

Vadim Chumel


Note that you probably want to make usernames unique, but also case-insensitive, so you don't end up with both username and Username:

class User < ApplicationRecord
  validates :username, presence: true, uniqueness: { case_sensitive: false }
  # Rest of user model
end

From the Devise wiki.

like image 4
antun Avatar answered Nov 12 '22 09:11

antun