0

I have added another login filled in devise, i.e. contact_no. Either email address or contact no. should provided. To make contact_no unique I added a check in my user model for uniquness.

validates_uniqueness_of :contact_no, allow_nil: true, allow_blank: true

But, it keeps throwing error

Mysql2::Error: Duplicate entry '' for key 'index_users_on_contact_no':
Shilpi Agrawal
  • 67
  • 1
  • 12

1 Answers1

1

This is because of allow_blank: true

Refer to this answer

MySql unique index allows multiple NULL values(if column is NULLable), however in your case, you have allow_blank set to true, which results in multiple empty strings "" inserted to table, which is causing that error

You can fix this by removing allow_blank: true and manually setting contact_no to nil when its blank

For ex:

# user.rb  
after_initialize :set_default, unless: persisted?

def set_default
   self.contact_no = nil if contact_no.nil? || contact_no.blank?
end
Sujan Adiga
  • 1,331
  • 1
  • 11
  • 20