Mongoid same embedded documents types for different fields

自闭症网瘾萝莉.ら 提交于 2019-12-13 14:28:55

问题


I am attempting to add embedded documents. I know this syntax is wrong but it demonstrates what I am 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

The code sample below works, but I am trying to avoid the code duplication.

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

Anyone know of a clean way to handle this?


回答1:


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



回答2:


I suppose 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


来源:https://stackoverflow.com/questions/10183544/mongoid-same-embedded-documents-types-for-different-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!