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

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

    By using custom validations we can do this operation

    validate :validate_address

    def validate_address
    errors.add(:permenent_address, "can't be the same as present_address") if self.present_address== self.permenent_address end

    0 讨论(0)
  • 2020-12-29 21:27

    New way:

    validates :password, exclusion: { in: lambda{ |user| [user.email] } }
    

    or:

    validates :password, exclusion: { in: ->(user) { [user.email] } }
    
    0 讨论(0)
  • 2020-12-29 21:28

    it is much wiser to use custom validator, here is code for universal validator that can be used

    class ValuesNotEqualValidator < ActiveModel::Validator
      def validate(record)
        if options[:fields].any? && options[:fields].size >= 2
          field_values = options[:fields].collect { |f| record.send(f) }
          unless field_values.size == field_values.uniq.size
            record.errors[:base] <<
                (options[:msg].blank? ? "fields: #{options[:fields].join(", ")} - should not be equal" :
                    options[:msg])
          end
        else
          raise "#{self.class.name} require at least two fields as options [e.g. fields: [:giver_id, :receiver_id]"
        end
      end
    end
    

    and then use it like:

    class User < ActiveRecord::Base
      # ...
      validates_with ValuesNotEqualValidator, fields: [:email, :password], msg: "This Person is evil"
    end
    
    0 讨论(0)
提交回复
热议问题