0
votes

I'm using rails 5.2 with devise. I have added a unique username field in my database for devise users. I'm getting ActiveRecord::RecordNotUnique error for my database when trying to signup with a duplicate username. I want to have an error message just like devise has default for emails. Thanks!

edit full error message:

PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_users_on_username" DETAIL: Key (username)=(supertest) already exists. : INSERT INTO "users" ("email", "encrypted_password", "created_at", "updated_at", "username") VALUES ($1, $2, $3, $4, $5) RETURNING "id"

1

1 Answers

2
votes

You need to add a validation to your model:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :confirmable, :recoverable, :validatable # ...
  validates_uniqueness_of :username
end

The validation prevents the low level ActiveRecord::RecordNotUnique exception since Rails will not attempt to write to the db if the validation fails.