简体   繁体   English

Rails validates_uniqueness_of除非自我验证

[英]Rails validates_uniqueness_of with unless validation on self

I'm using rails for authentication and want to validate the uniqueness of a username, unless the other username was set up as a temporary account. 我正在使用Rails进行身份验证,并且想要验证用户名的唯一性,除非将另一个用户名设置为临时帐户。

Example: We set up a user account that has name: "buddy" with email: "placeholder@email.com" 示例:我们设置了一个名称为“ buddy”的用户帐户,其电子邮件为:“ placeholder@email.com”

A user comes and creates an account. 用户来创建帐户。 We want the user to be able to user the name "buddy" if the only other buddy account is associated with email: "placehoder@gmail.com". 如果唯一的其他好友帐户与电子邮件关联:“ placehoder@gmail.com”,我们希望用户能够使用名称“ buddy”。

Bascially I want to do something along the lines of: 我基本上想按照以下方式做一些事情:

validates_uniqueness_of :name, unless: User.where(name: :name).first.email.include?("placeholder@email.com")

What is the correct way to do this? 正确的方法是什么?

您可以将Proc传递给exclude:选项,就像这样...

validates_uniqueness_of :name, unless: Proc.new { |user| User.where(name: user.name).first && User.where(name: user.name.first.email.include?(user.email) }
validates_uniqueness_of :name, conditions: -> {where.not(email: "placeholder@email.com")}

This will generate a query like 这将生成类似的查询

SELECT 1 AS one FROM "users"
  WHERE ("users"."name" = 'buddy') AND
        ("users"."email" != 'placeholder@email.com')
  LIMIT 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM