From 285b23f39765d8346a658a81eca8b70d70b3e9bf Mon Sep 17 00:00:00 2001 From: Azul Date: Tue, 18 Dec 2012 13:41:41 +0100 Subject: refactored email_alias creation and validation using CouchRests user.email_aliases.build so the casted_by method is set in the alias Used this to move the validations into the alias itself. This is where they belong and allows us to render the errors inline along the email field they belong to. --- users/app/models/local_email.rb | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'users/app/models/local_email.rb') diff --git a/users/app/models/local_email.rb b/users/app/models/local_email.rb index 7cca4f4..c654fcb 100644 --- a/users/app/models/local_email.rb +++ b/users/app/models/local_email.rb @@ -1,6 +1,9 @@ class LocalEmail < Email validate :unique_on_server + validate :unique_alias_for_user + validate :differs_from_main_email + validates :casted_by, :presence => true def to_partial_path "emails/email" @@ -9,7 +12,23 @@ class LocalEmail < Email def unique_on_server has_email = User.find_by_email_or_alias(email) if has_email && has_email != self.base_doc - errors.add(:email, "has already been taken") + errors.add :email, "has already been taken" end end + + def unique_alias_for_user + aliases = self.casted_by.email_aliases + if aliases.select{|a|a.email == self.email}.count > 1 + errors.add :email, "is already your alias" + end + end + + def differs_from_main_email + user = self.casted_by + if user.email == self.email + errors.add :email, "may not be the same as your email address" + end + end + + end -- cgit v1.2.3