I have the following case where I have a document that I need to embed in some documents, but for traceability (eg need to know the amount of people who is subscribed to each type) I need it to be stored as a different document. So when I try to save a default set of Types it says:
Mongoid::Errors::NoParent: Problem: Cannot persist embedded document Type without a parent document.
I don't know how to do it or how to handle this situation, any help or suggestion is appreciated.
class Type
include Mongoid::Document
embedded_in :typeable, polymorphic: true
belongs_to :client
field :count, type: Integer # number of people interested in each Type
end
class Client
include Mongoid::Document
has_many :types
embeds_many :discounts, as: :discountable
end
class Discount
include Mongoid::Document
embeds_many :types, as: :typeable
embedded_in :discountable, polymorphic: true
end
The simple answer is that you can't create standalone documents for an embedded model (you are architecturally preventing that by choosing to embed). If you need to have a standalone set of Types you should use has_many
and belongs_to
instead of embeds_many
and embedded_in
.
Have you thought about inheritance?
Make your Client
and Discount
models inherit from Type
.
They will benefit from your Type
fields and you will be able to have a standalone Type
index too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.