开发者

Referencing Mongoid recursively_embeds_many from another Document

开发者 https://www.devze.com 2023-04-04 16:04 出处:网络
I have two Document Models that are proving problematic: class Component include Mongoid::Document include Mongoid::Versioning

I have two Document Models that are proving problematic:

class Component
  include Mongoid::Document
  include Mongoid::Versioning

  recursively_embeds_many
end

class Institut开发者_如何学JAVAion
  include Mongoid::Document

  has_many :components
end

I understand that you shouldn't be able to reference an embedded model from another document. I'm hoping however that with the recursively embedded documents there's a way to reference the top of the tree from another document? If this is not possible to use these relationships together at all, what alternatives do I have to setup a one-to-many relationship between Institution and Component while maintaining the recursive nature of component?


What you are trying to do sounds reasonable but Mongoid won't let you associate a class that can be embedded with another class via an association. When I gave it a try I got an exception raised in this file (line 218) when adding a (top-level) Component to an Institution.

The simplest option for you would be to embed Component in Institution, e.g.

class Institution
  include Mongoid::Document

  embeds_many :components
end

Otherwise, if you want to share Component trees with different Institutions I guess you would need to introduce some kind of container object into the model and define a many-many association to Institution, e.g.:

class Component
  include Mongoid::Document
  include Mongoid::Versioning

  recursively_embeds_many
end

class ComponentTree
  include Mongoid::Document

  embeds_many :components
  has_and_belongs_to_many :institutions
end

class Institution
  include Mongoid::Document

  has_and_belongs_to_many :component_trees
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号