ruby-on-rails - 自定义电子邮件唯一验证不适用于设计

标签 ruby-on-rails ruby validation scope 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

但效果不佳。

用户模型与组织之间的关系: 应用程序/模型/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

结束

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

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

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

最佳答案

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

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

这对我有用。

关于ruby-on-rails - 自定义电子邮件唯一验证不适用于设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57569530/

相关文章:

ruby-on-rails - 尝试使用 React 在 Rails 应用程序上设置 ruby​​ 时出现 yarn 问题

ruby - 如何搜索二进制文件并用 Ruby 替换字符串?

ruby - $&、$'、$1 等在 Ruby 代码中是什么意思?

ruby-on-rails - Rails对模型属性的大于验证模型

php - check_phone 函数中的电话号码验证

python - Tkinter Spinbox 范围验证

ruby-on-rails - 如何在本地主机上的 PayPal 中获取 IPN 通知

ruby-on-rails - ruby /rails : difference between "@item" and "item" in a view

javascript - 用 Cucumber 以不显眼的方式测试 JavaScript?

Ruby 合并 n 个哈希元素并取中间键