3
votes

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.

1
can u add the schema for user relation ?? - Abhishek Aravindan
Please show what you mean by "not working". ie error message, or what you expected versus what actually happened. - mahemoff
I have added relation and schema as well. @mahemoff 'not working' mean validation not working as per required. - roshita
@mahemoff I have added problem example and error message in above question - roshita
Thanks. "another user in organization" Did you mean "a user in another organization"? Because if it's same organization, the error makes sense. - mahemoff

1 Answers

3
votes

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.