MongoMapper uses ActiveModel:Validations, so it works almost exactly like ActiveRecord.
class Person
include MongoMapper::Document
key :first_name, String
key :last_name, String
key :age, Integer
key :born_at, Time
key :active, Boolean
key :fav_colors, Array
validates_presence_of :first_name
validates_presence_of :last_name
validates_numericality_of :age
validate :custom_validation
def custom_validation
if age < 20
errors.add( :age, "Youth is wasted on the young")
end
end
endValidations are run when attempting to save a record. If validations fail, save will return false.
@person = Person.new(:first_name => "Jon", :last_name => "Kern", :age => 9)
if @person.save
puts "#{p.first_name} #{p.last_name} (age #{p.age})"
else
puts "Error(s): ", p.errors.map {|k,v| "#{k}: #{v}"}
end
# Error(s):
# age: Youth is wasted on the youngMost simple validations can be declared along with the keys.
class Person
include MongoMapper::Document
key :first_name, String, :required => true
key :last_name, String, :required => true
key :age, Integer, :numeric => true
key :born_at, Time
key :active, Boolean
key :fav_colors, Array
endThe available options when defining keys are:
validates_presence_ofvalidates_uniqueness_ofvalidates_numericality_ofvalidates_format_ofvalidates_inclusion_ofvalidates_exclusion_ofvalidates_length_of