Alex Zakruzhetskyi
Alex Zakruzhetskyi

Reputation: 1433

Skipping email validation for Devise gem causes a uniqueness error

In my Rails application, I use Devise gem for authenticating users. I need to skip email validation if I create a user from the admin panel. So far I have this code:

# User model
class User < ApplicationRecord
  attr_accessor :skip_email_validation

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable

  validates :email, presence: true, uniqueness: true, unless: :skip_email_validation
end

#User's controller create action
class Admin::UsersController < Admin::AdminController
  def create
    @user = User.new(user_params)
    @user.skip_email_validation = true
    if @user.save
      redirect_to admin_user_path(@user), success: 'User created.'
    else
      render :new
    end
  end
end

So, when I created the first user without email, it was saved into the database, but when I create another user without email, I have an error:

Mysql2::Error: Duplicate entry '' for key 'index_users_on_email': INSERT INTO `users`

I don't understand what is causing this error, because I skip the validation of presence and uniqueness in the model. Thanks ahead for an answer.

Upvotes: 1

Views: 158

Answers (1)

Kartikey Tanna
Kartikey Tanna

Reputation: 1459

You might need to make changes on the database level.

Devise uses unique index on Users table.

Devise has following in its migration:

add_index :users, :email, unique: true

which results in the following in your db/schema.rb

t.index ["email"], name: "index_users_on_email", unique: true

You need to change that in the migrations/schema and reset your database. `

Upvotes: 2

Related Questions