I can’t seem to figure out how to update or destroy EmbeddedDocuments in MongoMapper. Through Googling I’ve seen different methods like delete_if {} and others, but none seem to work for me semantically. Is there anything built-in to MongoMapper to help with this?
class Schedule
include MongoMapper::Document
key :name, String
key :description, String
key :active, Boolean, :default => false
many :periods
validates_presence_of :name
def activate!
set({:active => true}, :active => false)
self.active = true
end
end
class Period
include MongoMapper::EmbeddedDocument
key :number, Integer
key :text, String
key :start, Time
key :finish, Time
embedded_in :schedule
before_validation :number!
validates_presence_of :number
validates_presence_of :text
validates_presence_of :start
validates_presence_of :finish
validates_format_of :start, :with => /^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$/
validates_format_of :finish, :with => /^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$/
def number!
unless self.number
number = schedule.periods.count + 1
end
end
end
The follow test shows examples on how to update and remove embedded documents in two ways:
(1) via Ruby using standard Array accessors and methods, and
(2) via Mongo (MongoMapper / MongoDB) for update and removal of embedded documents on the DB server
References:
Note that Hash keys containing ‘.’ require use of the old ( => ) syntax. Hope that this helps.
test/unit/period_test.rb
output