0

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.

Example: We set up a user account that has name: "buddy" with email: "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".

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?

dmt2989
  • 1,610
  • 3
  • 17
  • 30

2 Answers2

1

You can pass a Proc to the unless: option, like so...

validates_uniqueness_of :name, unless: Proc.new { |user| User.where(name: user.name).first && User.where(name: user.name.first.email.include?(user.email) }
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53
  • Thanks. Slight modifications, but set me on the correct path: validates_uniqueness_of :name, unless: Proc.new { |user| User.where(name: user.name).first && User.where(name: user.name).first.email.include?("placeholder@gmail.com")} – dmt2989 Aug 13 '14 at 22:04
  • Ah, wow, `"placeholder@gmail.com"` is a literal! I didn't grasp that first read. Anyway, glad it helped. – SteveTurczyn Aug 13 '14 at 22:06
0
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
usha
  • 28,973
  • 5
  • 72
  • 93