Mongoid Custom Relation Between Embedded Documents
Imagine we have a Mongoid document, where we have two embedded documents. And now we want to make some relation between them. What you can think of at first is to use
1
has_many:acts,:foreign_key=>'event_id'
But that won't work. Mongoid is not capable at this moment to support this between embedded documents :(
But we can try to implement our own, custom relationship.
WARNING: This post is only my attempt to make it happen. It can contain bugs, or there can be other ways how to make it work easier. If you found some - let me know.
Overview
So let's say we have a main document called Event.
In Act we want to relate to one Area, so we need an field :area_id, type: String to track that. In Area document we will need to track array of acts, so we'll add field :act_ids, type: Array
Now, let's add some custom relationship management to Act document
defareaself.event.areas.find(self.area_id)rescuenilenddefarea_nameself.area.namerescuenilenddefarea_id=(value)act_id=self.id.to_sarea=self.areaifarea.nil?area=find_area_by_id(value)endreturnsuper(value)ifarea.nil?ifvalue.blank?area.pull(:act_ids,act_id)# remove old one elsearea.pull(:act_ids,act_id)area=find_area_by_id(value)area.add_to_set(:act_ids,act_id)endsuper(value)enddeffind_area_by_id(value)self.event.areas.find(value)rescuenilend#around_destroybefore_destroydo|document|#Handle callback here.area=self.areaarea.pull(:act_ids,self.id.to_s)ifareaend