1

I have the following case where I have a document that I need to embed in some documents, but for traceability (e.g 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
Mike S
  • 11,329
  • 6
  • 41
  • 76
sescob27
  • 647
  • 1
  • 8
  • 17

2 Answers2

0

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.

Mike S
  • 11,329
  • 6
  • 41
  • 76
0

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.

Mike S
  • 11,329
  • 6
  • 41
  • 76
jgburet
  • 535
  • 3
  • 15