Class: JSONAPI::ActiveRelationResource

Inherits:
BasicResource show all
Defined in:
lib/jsonapi/active_relation_resource.rb

Direct Known Subclasses

Resource

Instance Attribute Summary

Attributes inherited from BasicResource

#context

Class Method Summary collapse

Methods inherited from BasicResource

_abstract, _add_relationship, _allowed_filter?, _as_parent_key, _attribute_delegated_name, _attribute_options, _cache_field, _caching, _clear_cached_attribute_options, _clear_fields_cache, _default_primary_key, _exclude_links, _has_attribute?, _has_sort?, _immutable, #_model, _model_class, _model_name, _polymorphic, _polymorphic_name, _polymorphic_resource_klasses, _polymorphic_types, _primary_key, _relationship, _resource_name_from_type, _singleton_options, _table_name, _updatable_attributes, _updatable_relationships, abstract, attribute, attribute_caching_context, attribute_to_model_field, attributes, belongs_to, cache_field, #cache_id, caching, caching?, call_method_or_proc, cast_to_attribute_type, #change, creatable_fields, create, create_model, #create_to_many_links, #custom_links, default_attribute_options, default_sort, define_foreign_key_setter, define_on_resource, define_relationship_methods, exclude_link?, exclude_links, #fetchable_fields, fields, filter, filters, has_many, has_one, hash_cache_field, #id, #identity, immutable, inherited, #initialize, is_filter_relationship?, #is_new?, key_type, #meta, #model_error_messages, model_hint, model_name, module_path, mutable?, paginator, parse_exclude_links, polymorphic, primary_key, rebuild_relationships, register_relationship, relationship, #remove, #remove_to_many_link, #remove_to_one_link, #replace_fields, #replace_polymorphic_to_one_link, #replace_to_many_links, #replace_to_one_link, resource_for, resource_key_type, resource_klass_for, resource_klass_for_model, resource_type_for, resources_for, root?, root_resource, routing_options, routing_resource_options, singleton, singleton?, singleton_key, sort, sortable_field?, sortable_fields, sorts, updatable_fields, #validation_error_metadata, verify_custom_filter, verify_filter, verify_filters, verify_key, verify_keys, verify_relationship_filter

Methods included from Callbacks

included

Constructor Details

This class inherits a constructor from JSONAPI::BasicResource

Class Method Details

.apply_join(records:, relationship:, resource_type:, join_type:, options:) ⇒ Object

end ‘records` methods



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/jsonapi/active_relation_resource.rb', line 310

def apply_join(records:, relationship:, resource_type:, join_type:, options:)
  if relationship.polymorphic? && relationship.belongs_to?
    case join_type
    when :inner
      records = records.joins(resource_type.to_s.singularize.to_sym)
    when :left
      records = records.joins_left(resource_type.to_s.singularize.to_sym)
    end
  else
    relation_name = relationship.relation_name(options)
    case join_type
    when :inner
      records = records.joins(relation_name)
    when :left
      records = records.joins_left(relation_name)
    end
  end

  if relationship.use_related_resource_records_for_joins
    records = records.merge(self.records(options))
  end

  records
end

.count(filters, options = {}) ⇒ Integer

Counts Resources found using the ‘filters`

Parameters:

  • filters (Hash)

    the filters hash

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller

Returns:

  • (Integer)

    the count



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/jsonapi/active_relation_resource.rb', line 38

def count(filters, options = {})
  join_manager = ActiveRelation::JoinManager.new(resource_klass: self,
                                                 filters: filters)

  records = apply_request_settings_to_records(records: records(options),
                         filters: filters,
                         join_manager: join_manager,
                         options: options)

  count_records(records)
end

Counts Resources related to the source resource through the specified relationship

Parameters:

  • source_rid (ResourceIdentity)

    Source resource identifier

  • relationship_name (String | Symbol)

    The name of the relationship

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller

Returns:

  • (Integer)

    the count



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/jsonapi/active_relation_resource.rb', line 234

def count_related(source_rid, relationship_name, options = {})
  relationship = _relationship(relationship_name)
  related_klass = relationship.resource_klass

  filters = options.fetch(:filters, {})

  # Joins in this case are related to the related_klass
  join_manager = ActiveRelation::JoinManager.new(resource_klass: self,
                                                 source_relationship: relationship,
                                                 filters: filters)

  records = apply_request_settings_to_records(records: records(options),
                         resource_klass: related_klass,
                         primary_keys: source_rid.id,
                         join_manager: join_manager,
                         filters: filters,
                         options: options)

  related_alias = join_manager.join_details_by_relationship(relationship)[:alias]

  records = records.select(Arel.sql("#{concat_table_field(related_alias, related_klass._primary_key)}"))

  count_records(records)
end

.find(filters, options = {}) ⇒ Array<Resource>

Finds Resources using the ‘filters`. Pagination and sort options are used when provided

Parameters:

  • filters (Hash)

    the filters hash

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller

  • :sort_criteria (Hash)

    The ‘sort criteria`

  • :include_directives (Hash)

    The ‘include_directives`

Returns:

  • (Array<Resource>)

    the Resource instances matching the filters, sorting and pagination rules.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/jsonapi/active_relation_resource.rb', line 14

def find(filters, options = {})
  sort_criteria = options.fetch(:sort_criteria) { [] }

  join_manager = ActiveRelation::JoinManager.new(resource_klass: self,
                                                 filters: filters,
                                                 sort_criteria: sort_criteria)

  paginator = options[:paginator]

  records = apply_request_settings_to_records(records: records(options),
                         sort_criteria: sort_criteria,filters: filters,
                         join_manager: join_manager,
                         paginator: paginator,
                         options: options)

  resources_for(records, options[:context])
end

.find_by_key(key, options = {}) ⇒ Object

Returns the single Resource identified by ‘key`

Parameters:

  • key

    the primary key of the resource to find

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller



54
55
56
57
# File 'lib/jsonapi/active_relation_resource.rb', line 54

def find_by_key(key, options = {})
  record = find_record_by_key(key, options)
  resource_for(record, options[:context])
end

.find_by_keys(keys, options = {}) ⇒ Object

Returns an array of Resources identified by the ‘keys` array

Parameters:

  • keys (Array<key>)

    Array of primary keys to find resources for

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller



63
64
65
66
# File 'lib/jsonapi/active_relation_resource.rb', line 63

def find_by_keys(keys, options = {})
  records = find_records_by_keys(keys, options)
  resources_for(records, options[:context])
end

.find_fragments(filters, options = {}) ⇒ Hash{ResourceIdentity => {identity: => ResourceIdentity, cache: cache_field, attributes: => {name => value}}}

Finds Resource fragments using the ‘filters`. Pagination and sort options are used when provided. Retrieving the ResourceIdentities and attributes does not instantiate a model instance. Note: This is incompatible with Polymorphic resources (which are going to come from two separate tables)

Parameters:

  • filters (Hash)

    the filters hash

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller

  • :sort_criteria (Hash)

    The ‘sort criteria`

  • :include_directives (Hash)

    The ‘include_directives`

  • :attributes (Hash)

    Additional fields to be retrieved.

  • :cache (Boolean)

    Return the resources’ cache field

Returns:

  • (Hash{ResourceIdentity => {identity: => ResourceIdentity, cache: cache_field, attributes: => {name => value}}})

    the ResourceInstances matching the filters, sorting, and pagination rules along with any request additional_field values



92
93
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/jsonapi/active_relation_resource.rb', line 92

def find_fragments(filters, options = {})
  include_directives = options[:include_directives] ? options[:include_directives].include_directives : {}
  resource_klass = self
  linkage_relationships = to_one_relationships_for_linkage(include_directives[:include_related])

  sort_criteria = options.fetch(:sort_criteria) { [] }

  join_manager = ActiveRelation::JoinManager.new(resource_klass: resource_klass,
                                                 source_relationship: nil,
                                                 relationships: linkage_relationships,
                                                 sort_criteria: sort_criteria,
                                                 filters: filters)

  paginator = options[:paginator]

  records = apply_request_settings_to_records(records: records(options),
                         filters: filters,
                         sort_criteria: sort_criteria,
                         paginator: paginator,
                         join_manager: join_manager,
                         options: options)

  # This alias is going to be resolve down to the model's table name and will not actually be an alias
  resource_table_alias = resource_klass._table_name

  pluck_fields = [sql_field_with_alias(resource_table_alias, resource_klass._primary_key)]

  cache_field = attribute_to_model_field(:_cache_field) if options[:cache]
  if cache_field
    pluck_fields << sql_field_with_alias(resource_table_alias, cache_field[:name])
  end

  linkage_fields = []

  linkage_relationships.each do |name|
    linkage_relationship = resource_klass._relationship(name)

    if linkage_relationship.polymorphic? && linkage_relationship.belongs_to?
      linkage_relationship.resource_types.each do |resource_type|
        klass = resource_klass_for(resource_type)
        linkage_fields << {relationship_name: name, resource_klass: klass}

        linkage_table_alias = join_manager.join_details_by_polymorphic_relationship(linkage_relationship, resource_type)[:alias]
        primary_key = klass._primary_key
        pluck_fields << sql_field_with_alias(linkage_table_alias, primary_key)
      end
    else
      klass = linkage_relationship.resource_klass
      linkage_fields << {relationship_name: name, resource_klass: klass}

      linkage_table_alias = join_manager.join_details_by_relationship(linkage_relationship)[:alias]
      primary_key = klass._primary_key
      pluck_fields << sql_field_with_alias(linkage_table_alias, primary_key)
    end
  end

  model_fields = {}
  attributes = options[:attributes]
  attributes.try(:each) do |attribute|
    model_field = resource_klass.attribute_to_model_field(attribute)
    model_fields[attribute] = model_field
    pluck_fields << sql_field_with_alias(resource_table_alias, model_field[:name])
  end

  sort_fields = options.dig(:_relation_helper_options, :sort_fields)
  sort_fields.try(:each) do |field|
    pluck_fields << Arel.sql(field)
  end

  fragments = {}
  rows = records.pluck(*pluck_fields)
  rows.each do |row|
    rid = JSONAPI::ResourceIdentity.new(resource_klass, pluck_fields.length == 1 ? row : row[0])

    fragments[rid] ||= JSONAPI::ResourceFragment.new(rid)
    attributes_offset = 1

    if cache_field
      fragments[rid].cache = cast_to_attribute_type(row[1], cache_field[:type])
      attributes_offset+= 1
    end

    linkage_fields.each do |linkage_field_details|
      fragments[rid].initialize_related(linkage_field_details[:relationship_name])
      related_id = row[attributes_offset]
      if related_id
        related_rid = JSONAPI::ResourceIdentity.new(linkage_field_details[:resource_klass], related_id)
        fragments[rid].add_related_identity(linkage_field_details[:relationship_name], related_rid)
      end
      attributes_offset+= 1
    end

    model_fields.each_with_index do |k, idx|
      fragments[rid].attributes[k[0]]= cast_to_attribute_type(row[idx + attributes_offset], k[1][:type])
    end
  end

  if JSONAPI.configuration.warn_on_performance_issues && (rows.length > fragments.length)
    warn "Performance issue detected: `#{self.name.to_s}.records` returned non-normalized results in `#{self.name.to_s}.find_fragments`."
  end

  fragments
end

.find_included_fragments(source_rids, relationship_name, options) ⇒ Object



217
218
219
220
221
222
223
224
225
# File 'lib/jsonapi/active_relation_resource.rb', line 217

def find_included_fragments(source_rids, relationship_name, options)
  relationship = _relationship(relationship_name)

  if relationship.polymorphic? # && relationship.foreign_key_on == :self
    find_related_polymorphic_fragments(source_rids, relationship, options, true)
  else
    find_related_monomorphic_fragments(source_rids, relationship, options, true)
  end
end

Finds Resource Fragments related to the source resources through the specified relationship

Parameters:

  • source_rids (Array<ResourceIdentity>)

    The resources to find related ResourcesIdentities for

  • relationship_name (String | Symbol)

    The name of the relationship

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller

  • :attributes (Hash)

    Additional fields to be retrieved.

  • :cache (Boolean)

    Return the resources’ cache field

Returns:

  • (Hash{ResourceIdentity => {identity: => ResourceIdentity, cache: cache_field, attributes: => {name => value}, related: {relationship_name: [] }}})

    the ResourceInstances matching the filters, sorting, and pagination rules along with any request additional_field values



207
208
209
210
211
212
213
214
215
# File 'lib/jsonapi/active_relation_resource.rb', line 207

def find_related_fragments(source_rids, relationship_name, options = {})
  relationship = _relationship(relationship_name)

  if relationship.polymorphic? # && relationship.foreign_key_on == :self
    find_related_polymorphic_fragments(source_rids, relationship, options, false)
  else
    find_related_monomorphic_fragments(source_rids, relationship, options, false)
  end
end

.find_to_populate_by_keys(keys, options = {}) ⇒ Object

Returns an array of Resources identified by the ‘keys` array. The resources are not filtered as this will have been done in a prior step

Parameters:

  • keys (Array<key>)

    Array of primary keys to find resources for

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller



73
74
75
76
# File 'lib/jsonapi/active_relation_resource.rb', line 73

def find_to_populate_by_keys(keys, options = {})
  records = records_for_populate(options).where(_primary_key => keys)
  resources_for(records, options[:context])
end

.join_relationship(records:, relationship:, resource_type: nil, join_type: :inner, options: {}) ⇒ Object



352
353
354
355
356
357
358
# File 'lib/jsonapi/active_relation_resource.rb', line 352

def join_relationship(records:, relationship:, resource_type: nil, join_type: :inner, options: {})
  relationship_records = relationship_records(relationship: relationship,
                                              join_type: join_type,
                                              resource_type: resource_type,
                                              options: options)
  records.merge(relationship_records)
end

.records(options = {}) ⇒ ActiveRecord::Relation

The ‘ActiveRecord::Relation` used for finding user requested models. This may be overridden to enforce permissions checks on the request.

Parameters:

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller

Returns:

  • (ActiveRecord::Relation)


282
283
284
# File 'lib/jsonapi/active_relation_resource.rb', line 282

def records(options = {})
  records_base(options)
end

.records_base(_options = {}) ⇒ ActiveRecord::Relation

Base for the ‘records` methods that follow and is not directly used for accessing model data by this class. Overriding this method gives a single place to affect the `ActiveRecord::Relation` used for the resource.

Parameters:

  • options (Hash)

    a customizable set of options

Returns:

  • (ActiveRecord::Relation)


272
273
274
# File 'lib/jsonapi/active_relation_resource.rb', line 272

def records_base(_options = {})
  _model_class.all
end

.records_for_populate(options = {}) ⇒ ActiveRecord::Relation

The ‘ActiveRecord::Relation` used for populating the ResourceSet. Only resources that have been previously identified through the `records` method will be accessed. Thus it should not be necessary to reapply permissions checks. However if the model needs to include other models adding `includes` is appropriate

Parameters:

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller

Returns:

  • (ActiveRecord::Relation)


293
294
295
# File 'lib/jsonapi/active_relation_resource.rb', line 293

def records_for_populate(options = {})
  records_base(options)
end

The ‘ActiveRecord::Relation` used for the finding related resources. Only resources that have been previously identified through the `records` method will be accessed and used as the basis to find related resources. Thus it should not be necessary to reapply permissions checks.

Parameters:

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :context (Hash)

    The context of the request, set in the controller

Returns:

  • (ActiveRecord::Relation)


304
305
306
# File 'lib/jsonapi/active_relation_resource.rb', line 304

def records_for_source_to_related(options = {})
  records_base(options)
end

.relationship_records(relationship:, join_type: :inner, resource_type: nil, options: {}) ⇒ Object



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/jsonapi/active_relation_resource.rb', line 335

def relationship_records(relationship:, join_type: :inner, resource_type: nil, options: {})
  records = relationship.parent_resource.records_for_source_to_related(options)
  strategy = relationship.options[:apply_join]

  if strategy
    records = call_method_or_proc(strategy, records, relationship, resource_type, join_type, options)
  else
    records = apply_join(records: records,
                         relationship: relationship,
                         resource_type: resource_type,
                         join_type: join_type,
                         options: options)
  end

  records
end