2012-04-16 167 views
-1

我第一次使用Mongoid。我想存储一组包含to,cc和bcc收件人主题,正文和数组的电子邮件。例如:创建Mongoid嵌入式文档

{to: [{email: '[email protected]', name: 'Andrew'}], cc: ... 

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

+0

你究竟尝试了什么? – 2012-04-17 00:00:50

+0

您是否阅读过文档?它解释了如何做到这一点非常清楚:http://mongoid.org/docs/documents.html – 2012-04-17 00:03:09

+0

这个链接更好,我认为:http://mongoid.org/docs/relations/embedded/1-n.html – 2012-04-17 00:04:31

回答

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