簡體   English   中英

自定義電子郵件唯一驗證不適用於設計

[英]Custom email unique validation not working on devise

我需要驗證帶范圍的電子郵件,但設計它不起作用。 即使修改了電子郵件唯一性的索引,也不允許用戶根據范圍進行創建。

我嘗試在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

應用程序/模型/ 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

結束

我的問題是:我的用戶使用organatin 1中的電子郵件現在必須在組織2中添加另一個用戶使用相同的電子郵件。 這樣做我得到錯誤

ActiveRecord :: RecordInvalid:驗證失敗:已經收到電子郵件

我相信在添加驗證范圍后,我應該可以添加用戶相同的電子郵件。

對於電子郵件唯一驗證,您可以嘗試:在模型中定義以下內容:

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

這對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM