Validate field is unique compared to another field in same form

Go To StackoverFlow.com

0

Say I have two fields in a new or edit form:

<%= f.text_field :email %>
<%= f.text_field :parent_email %>

How, in my model, can I validate that parent_email is different from email? The exclusion option seems like it might work, but I can't figure out how to access the email field's value within the model. Do I need to implement this in the controller instead?

validates :parent_email, exclusion: self.email # doesn't work, nor does :email
2012-04-05 21:48
by LouieGeetoo


1

The following should work (but I guess there are cooler solutions out there):

class User
  validate  :email_differs_from_parent_email

  private
  def email_differs_from_parent_email
    if email == parent_email
      errors.add(:parent_email, "parent_email must differ from email") 
    end
  end
end
2012-04-05 21:54
by Deradon
That does it. As usual, I'm spoiled by all the automatic methods. Thank you - LouieGeetoo 2012-04-11 14:47
Ads