在设计中使用子域范围进行电子邮件唯一性验证

时间:2017-05-10 09:09:43

标签: ruby-on-rails api devise

我正在使用devise gem注册我的rails 5 API 现在我有问题是,如果子域名不同,我想注册相同的电子邮件地址用户,所以我的步骤是

1)更新用户索引

add_index :users, [:email, :subdomain], unique: true

2)在user.rb

devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, :confirmable
validates :email, uniqueness: {:scope => :subdomain}

现在在控制台

  • User.last

#<User id: 111, email: "test@gmail.com", subdomain: "test">

  • 使用相同的电子邮件和不同的子域
  • 创建新用户

User.create!(email: "test@gmail.com", subdomain: "test1")

错误

(0.2ms)  BEGIN
  User Exists (0.5ms)  SELECT  1 AS one FROM "users" WHERE 
 "users"."email" = $1 AND "users"."deleted_at" IS NULL AND 
 "users"."subdomain" = $2 LIMIT $3  [["email", 
 "test@gmail.com"], ["subdomain", "test1"], ["LIMIT", 1]]

  User Exists (0.3ms)  SELECT  1 AS one FROM "users" WHERE 
 "users"."email" = $1 AND "users"."deleted_at" IS NULL LIMIT $2  
 [["email", "test@gmail.com"], ["LIMIT", 1]]
 (0.1ms)  ROLLBACK
 ActiveRecord::RecordInvalid: Validation failed: Email has already been taken

我做错了什么?

1 个答案:

答案 0 :(得分:1)

由于您有validatable,请将以下内容添加到您的用户模型中:

validates :email, presence: true
validates :subdomain, presence: true
validates :email, uniqueness: {:scope => :subdomain}

def email_required?
  false
end

def email_changed?
  false
end

参考:https://github.com/plataformatec/devise/wiki/How-To%3a-Allow-users-to-sign-in-with-something-other-than-their-email-address