title: rails mongoid dynamc model fails
body: <p>I am using rails/mongodb as my backend server for my web application.</p>
  
  <p>My database needs to be very flexible - I need to be able to define new tables and modify them during runtime. So I created a model Entity and a model Column (belongs to Entity) so I can dynamically create new models with dynamic columns.</p>
  
  <p>To create/read/update the records I wrote a function which I can call with the entity record and it returns the class of the requested model:</p>
  
  <p>I call the function getObject with the Entity record:</p>
  
  <pre><code>entity = Entity.find_by(name: obj)
  datarecord = getObject(entity)
  </code></pre>
  
  <p>Using this function: </p>
  
  <pre><code>def getObject(entity)
  
    obj= Class.new() do
        include Mongoid::Document
        include Mongoid::Attributes::Dynamic
        store_in collection: entity.name.pluralize.downcase
  
        entity.columns.each do |column|
            field column[:fieldNameOrPath]
        end
  
        entity.relationships.each do |relationship|
          if relationship.typ =='Belongs To'
            e = Entity.find(relationship.relationship_id)
            belongs_to e.name.downcase
            default_scope { includes(e.name.downcase)}
          end
          if relationship.typ =='Has Many'
            e = Entity.find(relationship.relationship_id)
            has_many e.name.pluralize.downcase
          end
          if relationship.typ =='Has And Belongs To Many'
            e = Entity.find(relationship.relationship_id)
            has_and_belongs_to_many e.name.pluralize.downcase
          end
        end
  
  #     def as_json(options={})
  #        attrs = super(:include =&gt; [:user])
  #        attrs["user"]["id"] = attrs["user"]["_id"].to_s
  #        attrs
  #     end
       end
     end
     obj
  end
  </code></pre>
  
  <p>This works when I use the returned object obj to retrieve data:</p>
  
  <pre><code>render json: { result: datarecord.all()}
  </code></pre>
  
  <p>It also works for creating and updating new records. But as soon as my entity has 'Belongs To' relationship I get runtime errors:</p>
  
  <pre><code>NoMethodError (undefined method `demodulize' for nil:NilClass):
  </code></pre>
  
  <p>Or </p>
  
  <pre><code>NoMethodError (undefined method `constantize' for nil:NilClass):
  </code></pre>
  
  <p>I guess the issues is that I have no class defined for the related models?</p>
  
  <p>My second problem is that I want to have other records which this record belongs_to automatically loaded. In a static implementation I can achieve this definde a as_json method which includes the associated records (see the commented rows in my code). But I dont know how I can do this in my dynamic model.</p>
  
  <p>Any idea whats going wrong here and how to fix it? Not sure my way to implement this is the right weay anyway - perhaps there is a better way?</p>
  
  <p>Thanks,
  Michael</p>