Read all model relationships like belongs_to and has_many
541054
def read_associations_configuration
      [:has_one, :has_many, :belongs_to].each do |relation|
        if @config.keys.include? :"#{relation}"
          raise "Invalid #{relation} value" if not [Hash, Array, Symbol].include? @config[:"#{relation}"].class

          # We change the user format (Hash, Array or only one element) to Array
          if @config[:"#{relation}"].kind_of? Hash
            list_models = @config[:"#{relation}"].keys
          elsif @config[:"#{relation}"].kind_of? Array
            list_models = @config[:"#{relation}"]
            # Transform the array of model in a hash with his configuraion (empty, default values)
            @config[:"#{relation}"] = {}
            list_models.each do |model|
              @config[:"#{relation}"][model.to_sym] = {}
            end
          else
            list_models = [@config[:"#{relation}"]]
            # Transform the array of model in a hash with his configuraion (empty, default values)
            @config[:"#{relation}"] = {}
            list_models.each do |model|
              @config[:"#{relation}"][model.to_sym] = {}
            end
          end

          # Iterate inside the array and get and create the configuration to that relationship
          list_models.each do |model|
            # If the user set some configuration (:class_name for example), we use it
            if @config[:"#{relation}"][model.to_sym].kind_of? Hash
              config = @config[:"#{relation}"][model.to_sym]
            # If not, we create it
            else
              # Change sybol of the class name to hash configuration
              @config[:"#{relation}"][model.to_sym] = {}
              config = {}
            end

            # We set the default class_name if is not seted
            if config[:class_name].nil?
              @config[:"#{relation}"][model.to_sym][:class_name] = model.to_s.classify
            else
              @config[:"#{relation}"][model.to_sym][:class_name] = config[:class_name]
            end

            # If the association is belongs_to, we need to define the columns
            if relation.to_s == "belongs_to"
              if config[:polymorphic] == true
                @config[:columns][ :"#{model}_id" ] = { :type => :integer }
                @config[:columns][ :"#{model}_type" ] = { :type => :string }
              else
                @config[:columns][ config[:foreign_key] || :"#{model}_id" ] = { :type => :integer }
                @config[:"#{relation}"][model.to_sym][:foreign_key] = config[:foreign_key] || :"#{model}_id" if @config[:"#{relation}"][model.to_sym][:foreign_key].nil?
              end
            end
            # TODO: Continue adding rails features like:
            #       :autosave
            #       :class_name
            #       :conditions
            #       :counter_cache
            #       :dependent
            #       :foreign_key
            #       :include
            #       :polymorphic
            #       :readonly
            #       :select
            #       :touch
            #       :validate
          end
        end
      end
    end
21491
def _data(self):
        
        d = {}

        # Iterate all keys and values
        for k, v in self._row_values.items():
            # Split related model fields
            attrs = k.rsplit('__', 1)

            # Set value depending case
            if len(attrs) == 2:
                # Related model field, store nested
                fk, fn = attrs
                if fk not in d:
                    d[fk] = {}
                d[fk][fn] = v

            else:
                # Own model field, store directly
                d[k] = v

        # Return (+cache) data
        return d
518073
def model_attributes(model, ignored_tables, ignored_cols)
      return [] if model.abstract_class? && Rails::VERSION::MAJOR < 3

      if model.abstract_class?
        model.direct_descendants.reject {|m| ignored?(m.table_name, ignored_tables)}.inject([]) do |attrs, m|
          attrs.push(model_attributes(m, ignored_tables, ignored_cols)).flatten.uniq
        end
      elsif !ignored?(model.table_name, ignored_tables) && @existing_tables.include?(model.table_name)
        model.columns.reject { |c| ignored?(c.name, ignored_cols) }.collect { |c| c.name }
      else
        []
      end
    end
319526
def joins
      return nil if inner_joins.empty?
      inner_joins.collect do |inner_join|
        join_table_name = association_class(inner_join).table_name
        join_on_field = inner_join.last.to_s
        "INNER JOIN #{join_table_name} ON #{join_table_name}.id = #{table_name}.#{join_on_field}"
      end
    end
746372
public function associations()
    {
        if (!$this->associations) {
            if ($this->getService('rails.config')['use_cache']) {
                $this->associations = $this->getCachedData();
            } else {
                $this->associations = $this->getAssociationsData();
            }
        }
        return $this->associations;
    }
122970
def store_model_associations
      self.model_associations = model.reflect_on_all_associations.delete_if { |a| DEFAULT_SKIPPED_ASSOCIATIONS.include?(a.name.to_s) }
    end
484124
def _get_all_relationships(self):
        """"""
        relationships_all = set()
        for goterm in self.go2obj.values():
            if goterm.relationship:
                relationships_all.update(goterm.relationship)
            if goterm.relationship_rev:
                relationships_all.update(goterm.relationship_rev)
        return relationships_all
887758
def read_new_model(method_name)
      if @persistor && @persistor.respond_to?(:read_new_model)
        return @persistor.read_new_model(method_name)
      else
        opts = @options.merge(parent: self, path: path + [method_name])

        if method_name.plural?
          return new_array_model([], opts)
        else
          return new_model({}, opts)
        end
      end
    end
338243
def construct_has_many_or_belongs_to_attributes(reflection, association_class, table_ids)
      # Determine the alias used for remote_table_name, if any. In all cases this will already
      # have been assigned an ID in table_ids (either through being involved in a previous join,
      # or - if it's the first table in the query - as the default value of table_ids)
      remote_table_alias = remote_table_name = association_class.table_name
      remote_table_alias += "_#{table_ids[remote_table_name]}" unless table_ids[remote_table_name] == 1

      # Assign a new alias for the local table.
      local_table_alias = local_table_name = reflection.active_record.table_name
      if table_ids[local_table_name]
        table_id = table_ids[local_table_name] += 1
        local_table_alias += "_#{table_id}"
      else
        table_ids[local_table_name] = 1
      end

      conditions = ''
      # Add type_condition, if applicable
      conditions += " AND #{association_class.send(:type_condition).to_sql}" if association_class.finder_needs_type_condition?
      # Add custom conditions
      conditions += " AND (#{association_class.send(:sanitize_sql, reflection.options[:conditions])})" if reflection.options[:conditions]

      if reflection.macro == :belongs_to
        if reflection.options[:polymorphic]
          conditions += " AND #{local_table_alias}.#{reflection.options[:foreign_type]} = #{reflection.active_record.quote_value(association_class.base_class.name.to_s)}"
        end
        {
          :joins => reflection.options[:joins],
          :remote_key => "#{remote_table_alias}.#{association_class.primary_key}",
          :local_key => reflection.primary_key_name,
          :conditions => conditions
        }
      else
        # Association is has_many (without :through)
        if reflection.options[:as]
          conditions += " AND #{remote_table_alias}.#{reflection.options[:as]}_type = #{reflection.active_record.quote_value(reflection.active_record.base_class.name.to_s)}"
        end
        {
          :joins => "#{reflection.options[:joins]}",
          :remote_key => "#{remote_table_alias}.#{reflection.primary_key_name}",
          :local_key => reflection.klass.primary_key,
          :conditions => conditions
        }
      end
    end
346790
def _get_reverse_relationships(opts):
    
    # Note that we have a hack here to handle internal API differences for
    # this internal API across Django 1.7 -> Django 1.8.
    # See: https://code.djangoproject.com/ticket/24208

    reverse_relations = OrderedDict()
    for relation in get_all_related_objects(opts):
        accessor_name = relation.get_accessor_name()
        related = getattr(relation, 'related_model', relation.model)
        reverse_relations[accessor_name] = RelationInfo(
            model_field=None,
            related_model=related,
            to_many=relation.field.rel.multiple,
            to_field=_get_to_field(relation.field),
            has_through_model=False
        )

    # Deal with reverse many-to-many relationships.
    for relation in get_all_related_many_to_many_objects(opts):
        accessor_name = relation.get_accessor_name()
        related = getattr(relation, 'related_model', relation.model)
        reverse_relations[accessor_name] = RelationInfo(
            model_field=None,
            related_model=related,
            to_many=True,
            # manytomany do not have to_fields
            to_field=None,
            has_through_model=(
                (getattr(relation.field.rel, 'through', None) is not None) and
                not relation.field.rel.through._meta.auto_created
            )
        )

    return reverse_relations
154890
def polymorphic_belongs_to(*symbols, &block)
        options = symbols.extract_options!
        options.merge!(polymorphic: true)
        belongs_to(*symbols, options, &block)
      end
1309430
function hasMany(config) {
        var association;
        association = {
            type           : 'HAS_MANY',
            name           : config.name || config,
            cardinality    : 'many',
            targetModel    : config.targetModel || config,
            localProperty  : config.localProperty || 'id',
            targetProperty : config.targetProperty || (config + 'Id')
        };
        
        this.prototype[association.name] = function(callback){
            var model = this;
            var targetModel = window;
            association.targetModel.split('.').forEach(function (property) {
                targetModel = targetModel[property];
            });
            targetModel.all(function (data) {
                var result = data.filter(function (instance) {
                    return instance[association.targetProperty] === model[association.localProperty];
                });
                if (callback) {
                    callback(result);
                }
            });
        };
        
        return this;
    }
650176
def each_association( objectpath )
    begin
      @client.associators(objectpath).each do |assoc|
        yield assoc
      end
    rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace
    end
  end
1335110
def read  #:nodoc:
      form_ar_options
      use_default_or_unscoped do
        @resultset = if self.output_csv? || all_record_mode?
          relation = @relation
                     .includes(@ar_options[:include])
                     .joins(@ar_options[:joins])
                     .order(@ar_options[:order])
                     .group(@ar_options[:group])
                     .merge(@ar_options[:conditions])
          relation = add_references relation

          relation
        else
          # p @ar_options
          relation = @relation
                     .send(@options[:page_method_name], @ar_options[:page])
                     .per(@ar_options[:per_page])
                     .includes(@ar_options[:include])
                     .joins(@ar_options[:joins])
                     .order(@ar_options[:order])
                     .group(@ar_options[:group])
                     .merge(@ar_options[:conditions])

          relation = add_references relation

          relation
        end
      end
      invoke_resultset_callbacks
    end
1248386
def models(parent = nil)
      model_paths = Dir["#{Rails.root}/app/models/*_jobs/*.rb"]
      model_paths.each{ |path| require path }
      sanitized_model_paths = model_paths.map { |path| path.gsub(/.*\/app\/models\//, '').gsub('.rb', '') }
      model_constants = sanitized_model_paths.map do |path|
        path.split('/').map { |token| token.camelize }.join('::').constantize
      end
      model_constants.select { |model| superclasses(model).include?(::Ohm::Model) }

      if parent
        model_constants.select { |model| model.included_modules.include?(parent) }
      else
        model_constants
      end
    end
84286
def _traverse_relationship_objs(self, rel2src2dsts, goobj_child, goids_seen):
        """"""
        child_id = goobj_child.id
        goids_seen.add(child_id)
        ##A self.go2obj[child_id] = goobj_child
        # Update goids_seen and go2obj with child alt_ids
        for goid_altid in goobj_child.alt_ids:
            goids_seen.add(goid_altid)
            ##A self.go2obj[goid_altid] = goobj_child
        # Loop through relationships of child object
        for reltype, recs in goobj_child.relationship.items():
            if reltype in self.relationships:
                for relationship_obj in recs:
                    relationship_id = relationship_obj.id
                    rel2src2dsts[reltype][relationship_id].add(child_id)
                    # If relationship has not been seen, traverse
                    if relationship_id not in goids_seen:
                        self._traverse_relationship_objs(rel2src2dsts, relationship_obj, goids_seen)
1284745
def related_to(self, instance):
        """"""
        return self.filter(table_name=instance.table_name, record_id=instance.record_id)