Mongoidal built-in document types for different fields

I am trying to add embedded documents. I know this syntax is incorrect, but it demonstrates what I'm trying to accomplish.

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

Below is the sample code below, but I try to avoid duplicate code.

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

Does anyone know of a clean way to handle this?

+3
source share
2 answers

Here is the best answer!

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
+4
source

I believe this may be the best solution.

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
0
source

All Articles