创建Mongoid嵌入式文档

时间:2012-04-16 23:59:41

标签: ruby mongodb mongoid

我第一次使用Mongoid。我想存储一组电子邮件,这些电子邮件包含主题,正文以及to,cc和bcc收件人的数组。例如:

{to: [{email: 'andrew@example.com', name: 'Andrew'}], cc: ...

但是,我似乎无法弄清楚如何使用Mongoid建模这些数据。我认为这些术语称为嵌入式文档,但我尝试过的所有内容似乎都不正常。如何使用Mongoid正确创建模型?

1 个答案:

答案 0 :(得分:2)

这是解决方案。如果要为多个字段重用一个类,则可以指定类名:

class Email
  include Mongoid::Document

  embeds_many :to_recipients, :class_name => "Recipient"
  embeds_many :cc_recipients, :class_name => "Recipient"
  embeds_many :bcc_recipients, :class_name => "Recipient"    
  embeds_one :from, :class_name => "Recipient"

  field :subject, type: String
  field :body_text, type: String
  field :body_html, type: String
end

class Recipient
  include Mongoid::Document
  field :email_address, type: String
  field :name, type: String
  validates :email_address, :presence => true
  embedded_in :emails
end