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

前端 未结 9 1631
既然无缘
既然无缘 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:12

    It depends how Your password is stored:

    class User < ActiveRecord::Base
        validate :email_and_password_validation
    
        def email_and_password_validation
            if self.email == self.password
                errors.add_to_base("Password must be different from email") 
            end
        end
    end
    

    This would work if Your password is stored literally, but You can perform the same thing with email (e.g. create a hashed version) and check for equality with password. E.g:

    class User < ActiveRecord::Base
        validate :email_and_password_validation
    
        def email_and_password_validation
            if make_hash(self.email) == self.hashed_password
                errors.add_to_base("Password must be different from email") 
            end
        end
    end
    

    My example is taken from http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002162

    Your situation is quite general so You can be interested in creating custom validation method. Everything is covered here: http://guides.rubyonrails.org/active_record_validations_callbacks.html#creating-custom-validation-methods

提交回复
热议问题