ruby-on-railsvalidationdatabase-integrity

how do i add a rails validation that negates existing rows


We have a standard email validation on a User model. The requirements change and say the new validation checks the format with a regexp, to not allow dashes in the emails.

Problem is, how do i avoid checking for existing users in the system that have dashes (which we want to keep allowing for now).

If I apply the validation on the model it wont let me save any other field in the user till email field validates.

How to i work around this? What's the best practice for a case like this?


Solution

  • I would probably do:

    validates :email, format: { with: <new_format_regex> }, if: email_changed?
    

    Adding if: email_changed? will trigger this validation only if email is changed. Hence it will not trigger for the existing users, unless they try to change their password and it will trigger for all new users creating theirs accounts.