【问题标题】:Creating Mongoid embedded documents创建 Mongoid 嵌入文档
【发布时间】:2012-04-16 23:59:41
【问题描述】:

我是第一次使用 Mongoid。我想存储具有主题、正文和收件人、抄送和密件抄送收件人数组的电子邮件集合。示例:

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

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

【问题讨论】:

标签: ruby mongodb mongoid


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    相关资源
    最近更新 更多