Rails model with integrated Mongolide and standalone

How to create a Mongolian model that can be stored in its own collection, and be embedded in another document?

+4
source share
1 answer

Short answer: you cannot.

When you use the inline relationship between two Mongoid documents, this is because you do not want the child model to be in its own collection. An embedded document in the literal sense is: embedded in its parent.

I'm not sure that you are new to Mongoid, so what you can really find is a link that behaves like a traditional RDBMS link, where the child document stores a link to the ID of the parent document.The Mongoid documentation for this starts here .

It is very easy to switch between them, given these built-in models:

class Person include Mongoid::Document field :name embeds_many :phone_numbers end class PhoneNumber include Mongoid::Document field :area_code field :number embedded_in :person end 

You can simply change embeds_many and embedded_in so that it becomes:

 class Person include Mongoid::Document field :name has_many :phone_numbers end class PhoneNumber include Mongoid::Document field :area_code field :number belongs_to :person end 

And it will just work. Now you can do things like query directly for phone numbers, with expressions such as: PhoneNumber.where(:area_code => "212") .

+6
source

All Articles