Search code examples
rubymongomapperpadrino

Added to existing EmbeddedDocuments in MongoMapper


Take the following MongoMapper documents.

class Schedule
  include MongoMapper::Document

  key :name, String
  key :description, String
  key :active, Boolean

  many :periods

  timestamps!
  userstamps!
end

class Period
  include MongoMapper::EmbeddedDocument

  key :number, Integer
  key :descriptor, String
  key :begin, Time
  key :end, Time
end

Also, take the following Padrino routing.

post :period, :map => '/schedule/period' do
  s = Schedule.first(params[:id])
  s.periods = [
    :number => 1,
    :descriptor => "This is a description.",
    :begin => Time.now,
    :end => Time.now
  ]
end

But, if I already have several periods within the schedule, won't I just be overwriting the existing periods? How can I avoid this?


Solution

  • Alas, association methods haven't been documented yet on mongomapper.com. But...

    Use the concat operator, which is defined on associations:

    s.periods << {
      :number => 1,
      :descriptor => "This is a description.",
      :begin => Time.now,
      :end => Time.now
    }
    

    You can hand it either a Hash or a document.