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

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

提交回复
热议问题