How do I validate that two values do not equal each other in a Rails model?

前端 未结 9 1636
既然无缘
既然无缘 2020-12-29 20:31

I have a User model, which has an email and a password field. For security, these may not be equal to each other. How can I define this in my model?

9条回答
  •  春和景丽
    2020-12-29 21:15

    You can use a custom validation method to check this.

    class User < ActiveRecord::Base
      # ...
    
      def validate
        if (self.email == self.password)
          errors.add(:password, "password cannot equal email")
          errors.add(:email, "email cannot equal password")
        end
      end
    end
    

提交回复
热议问题