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?
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
New way:
validates :password, exclusion: { in: lambda{ |user| [user.email] } }
or:
validates :password, exclusion: { in: ->(user) { [user.email] } }
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