I am trying to understand the relationships in mongoid and not able to move past the following:
class Band
  include Mongoid::Document
  embeds_many :photos
end
class Photo
  include Mongoid::Document
  embedded_in :Band
end
In the above code, Instructing Band to embed_many phtos shall store full photo data inside Band. However, what is the need to put embedded_in inside Photo class? If we do not put embedded_in in Photo, will it not be polymorphic automatically?
Also, will the query Photo.all fetch photos embedded inside Bands? If yes, Is this the reason for embedded_in? Can we have multiple embedded_in's for one class?
The embedded_in call is needed to add the methods to the Photo class so that you can access the band in which the photo is embedded. Just like you use has_many and belongs_to although the foreign key is only stored in the object that has a belongs_to. It also adds methods to check if the Photo is persisted and so on. And yes, you can have multiple embedded_in for one class.
Photo.all will not give you the photos that are embedded inside other classes. Normaly, if you only access a model through another, you'd embed it. It's cheaper to fetch the whole document at once than have another round-trip to the database when using a relation with a foreign key. So if you need something like Photo.all you should not embed Photo.
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