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?
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:
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 just change the embeds_many
and embedded_in
, so 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'll be able to do things like query directly for phone numbers with statements like: PhoneNumber.where(:area_code => "212")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With