How would I create a Mongoid model that has the ability to be saved in it’s own collection, and be embedded in another document?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The short answer: you can’t.
When you use an embedded relationship between two Mongoid documents, this is because you don’t want the child model in its own collection. An embedded document it literally that: embedded in its parent.
I’m not sure if you’re new to Mongoid, so what you may actually be looking for is a referenced relationship, which behaves more like a traditional RDBMS relationship, where the child document stores a reference to the parent document’s ID. The Mongoid documentation for this starts here.
It’s pretty easy to switch between the two, given these embedded models:
You can just change the
embeds_manyandembedded_in, so it becomes:And it will just work. Now you’ll be able to do things like query directly for phone numbers with statements like:
PhoneNumber.where(:area_code => "212").