我是第一次使用 Mongoid。我想存储具有主题、正文和收件人、抄送和密件抄送收件人数组的电子邮件集合。例子:
{to: [{email: 'andrew@example.com', name: 'Andrew'}], cc: ...
但是,我似乎无法弄清楚如何使用 Mongoid 对这些数据进行建模。我认为这些术语称为嵌入式文档,但我尝试过的所有内容似乎都无法正常工作。如何使用 Mongoid 正确创建模型?
这是解决方案。如果要为多个字段重用一个类,可以指定类名:
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