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?
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'