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

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

    If you want to support multiple languages, you have to come up with another solution, which translates the error messages and the attribute names. So I created a new each validator for that.

    validators/values_not_equal_validator.rb:
    class ValuesNotEqualValidator < ActiveModel::EachValidator
      def validate(record)
        @past = Hash.new
        super
      end
    
      def validate_each(record, attribute, value)
        @past.each do |k, v|
          if v == value
            record.errors.add(attribute, I18n.t('errors.messages.should_not_be_equal_to') + " " + record.class.human_attribute_name(k))
          end
        end
        @past[attribute] = value
      end
    end
    

    I call it in the model like this:

    class User < ActiveRecord::Base
      validates :forename, :surname, values_not_equal: true
    end
    

    And I translate it the messages like this:

    de:
      activerecord:
        attributes:
          user:
            forename: 'Vorname'
            surname: 'Nachname'
      errors:
        messages:
          should_not_be_equal_to: 'darf nicht gleich sein wie'
    

提交回复
热议问题