3

我正在尝试添加嵌入式文档。我知道这种语法是错误的,但它展示了我想要完成的事情。

class Email
  include Mongoid::Document

  embeds_many :recipients, as: :to
  embeds_many :recipients, as: :cc
  embeds_many :recipients, as: :bcc

  field :from, type: String
  field :subject, type: String
  field :body, 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

下面的代码示例有效,但我试图避免代码重复。

class Email
  include Mongoid::Document

  embeds_many :to_recipients
  embeds_many :cc_recipients
  embeds_many :bcc_recipients

  field :from, type: String
  field :subject, type: String
  field :body, type: String
end

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

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

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

任何人都知道一个干净的方法来处理这个?

4

2 回答 2

4

这里是最佳答案!

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
于 2012-04-18T18:23:13.133 回答
0

我想这可能是最好的解决方案

class Email
  include Mongoid::Document

  embeds_many :to_recipients
  embeds_many :cc_recipients
  embeds_many :bcc_recipients

  field :from, type: String
  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


class ToRecipient < Recipient; end
class CcRecipient < Recipient; end
class BccRecipient < Recipient; end
于 2012-04-17T15:00:02.270 回答