Sha256: c403a7b91567c94403f3bd561b68b0826ae9dc7c02b4cf2cb8e117916f26fb45

Contents?: true

Size: 1.41 KB

Versions: 2

Compression:

Stored size: 1.41 KB

Contents

module ROM
  module SQL
    class Association
      class OneToMany < Association
        result :many

        # @api public
        def call(relations)
          with_keys(relations) do |left_pk, right_fk|
            right = relations[target.relation]
            columns = right.header.qualified.to_a

            relation = right
              .inner_join(source, left_pk => right_fk)
              .select(*columns)
              .order(*right.header.project(*right.primary_key).qualified)

            relation.with(attributes: relation.header.names)
          end
        end

        # @api public
        def combine_keys(relations)
          Hash[*with_keys(relations)]
        end

        # @api public
        def join_keys(relations)
          with_keys(relations) { |source_key, target_key|
            { qualify(source, source_key) => qualify(target, target_key) }
          }
        end

        # @api private
        def associate(relations, child, parent)
          pk, fk = join_key_map(relations)
          child.merge(fk => parent.fetch(pk))
        end

        protected

        # @api private
        def with_keys(relations, &block)
          source_key = relations[source.relation].primary_key
          target_key = relations[target.relation].foreign_key(source.relation)
          return [source_key, target_key] unless block
          yield(source_key, target_key)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rom-sql-0.9.1 lib/rom/sql/association/one_to_many.rb
rom-sql-0.9.0 lib/rom/sql/association/one_to_many.rb