class User include MongoMapper::Document end class Address include MongoMapper::EmbeddedDocument embedded_in: user key :city validates_presence_of :user end
user.address.city = nil user.address.valid? #=> false user.valid? # => true user.save! #=> does not raise error user.reload user.address.city #=> nil
本家の issue No validation in EmbbededDocument · Issue #109 · mongomapper/mongomapper · GitHub では親モデルで validate しろ的な回答がされているが、うーん、それもどうなんだと思っていると stackoverflow に別解あった。
ruby on rails 3 - Mongomapper: Embedded document does not work properly - Stack Overflow
親モデルに validates_associated
を設定してやればよい。
class User include MongoMapper::Document validates_associated :user end
user.address.city = nil user.address.valid? #=> false user.valid? # => false user.save! #=> MongoMapper::DocumentNotValid: Validation failed: Address is invalid