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