Method: Caprese::Query#record_for_resource_identifier

Defined in:
lib/caprese/controller/concerns/query.rb

#record_for_resource_identifier(resource_identifier) ⇒ ActiveRecord::Base

Given a resource identifier, finds or builds a resource

Parameters:

  • resource_identifier (Hash)

    the resource identifier for the resource

Returns:

  • (ActiveRecord::Base)

    the found or built resource for the relationship



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/caprese/controller/concerns/query.rb', line 94

def record_for_resource_identifier(resource_identifier)
  if (type = resource_identifier[:type])
    # { type: '...', id: '...' }
    if (id = resource_identifier[:id])
      begin
        get_record!(
          type,
          Caprese.config.resource_primary_key,
          id
        )
      rescue RecordNotFoundError => e
        raise e unless record_scope(type.to_sym).is_a?(ActiveRecord::NullRelation)
      end

      # { type: '...', attributes: { ... } }
    elsif contains_constructable_data?(resource_identifier)
      record_scope(type.to_sym).build

      # { type: '...' }
    else
      raise RequestDocumentInvalidError.new(field: :base)
    end
  else
    # { id: '...' } && { attributes: { ... } }
    raise RequestDocumentInvalidError.new(field: :type)
  end
end