Mongomapper can use EmbeddedDocuments inside its Documents. There are some advances and disadvantages to it. This post is about validations for EmbeddedDocuments. If you have two classes like this:
class Address
include MongoMapper::EmbeddedDocument
key :address, String, :required => true
end
class Person
include MongoMapper::Document
many :addresses
end
You can add addresses to Person like this:
person = Person.new
person.addresses << Address.new(:address => 'Home sweet home')
person.save
Which is fine and probably exactly what you want.
Aside, there is currently a bug in 0.10.2 which does not show addresses if you inspect person
. It will give you a nil
on addresses which is not true. In the db the value is correctly set.
However, assume you have an invalid address like this one:
person.addresses << Address.new
person.save
person.addresses
The address will be saved in person even though the address is invalid. Unless you specifically ask for its validity before you save you can't be sure.
In this case you might want to do something like this:
address = Address.new(your_attributes)
person.addresses << address
raise unless address.valid? && person.save
This will add the address to person and then check in one go if the address was valid and if person saved it.