本文介绍了Mongoid用于不同领域的相同嵌入式文档类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试添加嵌入式文档.我知道这种语法是错误的,但是它演示了我要完成的工作.
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?
推荐答案
这是最好的答案!
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
这篇关于Mongoid用于不同领域的相同嵌入式文档类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!