Reputation: 1620
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: "[email protected]"
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: "[email protected]".
Bascially I want to do something along the lines of:
validates_uniqueness_of :name, unless: User.where(name: :name).first.email.include?("[email protected]")
What is the correct way to do this?
Upvotes: 0
Views: 392
Reputation: 36860
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) }
Upvotes: 1
Reputation: 29349
validates_uniqueness_of :name, conditions: -> {where.not(email: "[email protected]")}
This will generate a query like
SELECT 1 AS one FROM "users"
WHERE ("users"."name" = 'buddy') AND
("users"."email" != '[email protected]')
LIMIT 1
Upvotes: 0