添加到MongoMapper中的现有EmbeddedDocuments

时间:2011-06-05 13:53:49

标签: ruby mongomapper padrino

获取以下MongoMapper文档。

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

另外,请采用以下Padrino路由。

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

但是,如果我在时间表中已经有多个periods,我是否只会覆盖现有的periods?我怎么能避免这个?

1 个答案:

答案 0 :(得分:1)

唉,mongomapper.com上尚未记录关联方法。但...

使用concat运算符,该运算符在关联上定义:

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

您可以将其交给哈希或文档。