roshita
roshita

Reputation: 175

Custom email unique validation not working on devise

I need to validate email with scope but with devise it is not working. Even after modifying index for email uniqueness it is not allowing user to create on basis of scope.

i have tried adding following line on config/initializers/devise.rb

config.authentication_keys=[:email, :organization_id]

But it doesnot work.

Also i have tried with validation on model:

 validates_uniqueness_of :email, scope: :organization_id

But it doesnot work.

Also tried by modifying user migration:

def up
  remove_index :users, name: 'index_users_on_email'
  add_index :users, [:email, :organization_id], unique: true
end

But it doesnot work as well.

Relation between user model an organization: app/models/organization.rb

Class Organization < ApplicationRecord
  has_many :users
end

app/models/user.rb

class User < ApplicationRecord
  belongs_to :organization
end

Here is schema :

create_table "users", force: :cascade do |t|
t.string "type"
t.string "full_name"
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "authentication_token", limit: 30
t.integer "organization_id"
t.string "archive_number"
t.datetime "archived_at"
t.index ["authentication_token"], name: "index_users_on_authentication_token", unique: true
t.index ["email" , "organization_id"], name: "index_users_on_email_and_organization_id", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

My problem was that: I have user with email in organizatin 1 now is have to add another user in organization 2 with same email. While doing this i am getting error

ActiveRecord::RecordInvalid: Validation failed: Email has already been taken

I belive that i should be able to add user with same email after adding scope under validation.

Upvotes: 3

Views: 960

Answers (1)

Rasna Shakya
Rasna Shakya

Reputation: 557

For the email unique validation, you can try this: Define following in your model:

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  validates_uniqueness_of :email, scope: :organization

  def will_save_change_to_email?
    false
  end

  def email_changed?
    false
  end
end

This worked for me.

Upvotes: 4

Related Questions