Sha256: bd92400a7c935863a12159b237a1b82f625c6ae0bbe55c591d521358b1763ea8

Contents?: true

Size: 1.15 KB

Versions: 7

Compression:

Stored size: 1.15 KB

Contents

module GraphitiGql
  module Loaders
    class ManyToMany < Many
      def assign(parent_records, proxy)
        thru = @sideload.foreign_key.keys.first
        fk = @sideload.foreign_key[thru]
        add_join_table_magic(proxy)
        records = proxy.data
        parent_records.each do |pr|
          corresponding = records.select do |record|
            record.send(:"_edge_#{fk}") == pr.send(@sideload.primary_key)
          end
          fulfill(pr, [corresponding, proxy])
        end
      end

      private

      def add_join_table_magic(proxy)
        if defined?(ActiveRecord) && proxy.resource.model.ancestors.include?(ActiveRecord::Base)
          thru = @sideload.foreign_key.keys.first
          reflection = @sideload.parent_resource.model.reflect_on_association(thru)
          thru_model = reflection.klass

          names = thru_model.column_names.map do |n|
            next if n == :id
            "#{thru_model.table_name}.#{n} as _edge_#{n}"
          end
          scope = proxy.scope.object
          scope = scope.select(["#{proxy.resource.model.table_name}.*"] + names)
          proxy.scope.object = scope
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
graphiti_gql-0.2.12 lib/graphiti_gql/loaders/many_to_many.rb
graphiti_gql-0.2.11 lib/graphiti_gql/loaders/many_to_many.rb
graphiti_gql-0.2.10 lib/graphiti_gql/loaders/many_to_many.rb
graphiti_gql-0.2.9 lib/graphiti_gql/loaders/many_to_many.rb
graphiti_gql-0.2.8 lib/graphiti_gql/loaders/many_to_many.rb
graphiti_gql-0.2.7 lib/graphiti_gql/loaders/many_to_many.rb
graphiti_gql-0.2.6 lib/graphiti_gql/loaders/many_to_many.rb