【问题标题】:Custom email unique validation not working on devise自定义电子邮件唯一验证不适用于设计
【发布时间】:2019-12-25 10:16:51
【问题描述】:

我需要使用范围验证电子邮件,但使用设计它不起作用。即使修改了电子邮件唯一性的索引,它也不允许用户根据范围创建。

我尝试在 config/initializers/devise.rb 上添加以下行

config.authentication_keys=[:email, :organization_id]

但它不起作用。

我也尝试过对模型进行验证:

 validates_uniqueness_of :email, scope: :organization_id

但它不起作用。

也尝试通过修改用户迁移:

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

但它也不起作用。

用户模型与组织之间的关系: app/models/organization.rb

Class Organization < ApplicationRecord
  has_many :users
end

app/models/user.rb

class User < ApplicationRecord
  belongs_to :organization
end

这是架构:

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

结束

我的问题是: 我现在在组织 1 中有使用电子邮件的用户,现在必须在组织 2 中使用相同的电子邮件添加另一个用户。这样做时我收到错误

ActiveRecord::RecordInvalid:验证失败:电子邮件已经 拍摄

我相信我应该能够在添加验证范围后添加具有相同电子邮件的用户。

【问题讨论】:

  • 你可以添加用户关系的架构吗??
  • 请说明您所说的“不工作”是什么意思。即错误消息,或者您的预期与实际发生的情况。
  • 我也添加了关系和模式。 @mahemoff '不工作'意味着验证没有按要求工作。
  • @mahemoff 我在上述问题中添加了问题示例和错误消息
  • 谢谢。 “组织中的另一个用户”您的意思是“另一个组织中的用户”吗?因为如果是同一个组织,错误是有道理的。

标签: ruby-on-rails ruby validation scope devise


【解决方案1】:

对于电子邮件唯一性验证,您可以尝试以下操作: 在您的模型中定义以下内容:

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

这对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多