Search code examples
ruby-on-railsrubymongoidmodelsrelationships

How can I model a polymorphic, custom name relationship using Mongoid


I'm attempting to define a series of model relationships using custom names for a model in some instances, and it's native name in others. Furthermore, the model can be referenced by multiple classes, necessitating a polymorphic relationship.

The following models are simplified (I've removed fields, additional relationships, etc.), but they exemplify the structure I'm attempting to produce while avoid creating inherited models.

class Gallery
  include Mongoid::Document
  embedded_in :galleryable, polymorphic: true
end

class App
  include Mongoid::Document
  embeds_one  :about, class_name: 'Gallery', inverse_of: :galleryable
  embeds_one  :portfolio
end

class Portfolio
  include Mongoid::Document
  embedded_in :app
  embeds_many :galleries, as: :galleryable
end

I understand that the "child" being embedded by a custom relation should also have a class_name definition and an inverse_of:, but how can I define these values without needing to explicitly define the associated class?


Solution

  • You just have to define the association property ":as" :

      class Gallery
        include Mongoid::Document
        embedded_in :galleryable, polymorphic: true
      end
    
      class App
        include Mongoid::Document
        embeds_one  :about, as: :galleryable
        embeds_one  :portfolio
      end
    
      class Portfolio
        include Mongoid::Document
        embedded_in :app
        embeds_many :galleries, as: :galleryable
      end
    

    Hope it helps!