Sha256: 7d8029b131aa125e9029fffa3671b99cfa6b4472a497773c0c586676536aa017

Contents?: true

Size: 799 Bytes

Versions: 1

Compression:

Stored size: 799 Bytes

Contents

class JsonapiCompliable::Sideload::BelongsTo < JsonapiCompliable::Sideload
  def type
    :belongs_to
  end

  def load_params(parents, query)
    query.to_hash.tap do |hash|
      hash[:filter] ||= {}
      hash[:filter][primary_key] = ids_for_parents(parents)
    end
  end

  def assign_each(parent, children)
    children.find { |c| c.send(primary_key) == parent.send(foreign_key) }
  end

  def ids_for_parents(parents)
    parent_ids = parents.map(&foreign_key)
    parent_ids.compact!
    parent_ids.uniq!
    parent_ids
  end

  def infer_foreign_key
    if polymorphic_child?
      parent.foreign_key
    else
      model = resource.model
      namespace = namespace_for(model)
      model_name = model.name.gsub("#{namespace}::", '')
      :"#{model_name.underscore}_id"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
jsonapi_compliable-1.0.alpha.2 lib/jsonapi_compliable/sideload/belongs_to.rb