Class: ForestAdminAgent::Routes::Resources::Related::AssociateRelated

Inherits:
AbstractRelatedRoute show all
Includes:
Builder, ForestAdminDatasourceToolkit::Components::Query, ForestAdminDatasourceToolkit::Utils
Defined in:
lib/forest_admin_agent/routes/resources/related/associate_related.rb

Instance Method Summary collapse

Methods inherited from AbstractRelatedRoute

#build

Methods inherited from AbstractAuthenticatedRoute

#build, #format_attributes, #redacted_full_projection, #redacted_projection_with_pks

Methods inherited from AbstractRoute

#add_route, #build, #initialize, #routes

Constructor Details

This class inherits a constructor from ForestAdminAgent::Routes::AbstractRoute

Instance Method Details

#handle_request(args = {}) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/forest_admin_agent/routes/resources/related/associate_related.rb', line 23

def handle_request(args = {})
  context = build(args)
  context.permissions.can?(:edit, context.child_collection)

  parent_primary_key_values = Utils::Id.unpack_id(context.collection, args[:params]['id'], with_key: true)
  target_primary_key_values = Utils::Id.unpack_id(context.child_collection, args[:params]['data'][0]['id'],
                                                  with_key: true)
  relation = Schema.get_to_many_relation(context.collection, args[:params]['relation_name'])
  Collection.assert_writable_relation!(args[:params]['relation_name'], relation)

  case relation.type
  when 'OneToMany'
    associate_one_to_many(relation, parent_primary_key_values, target_primary_key_values, context)
  when 'ManyToMany'
    associate_many_to_many(relation, parent_primary_key_values, target_primary_key_values, context)
  when 'PolymorphicOneToMany'
    associate_polymorphic_one_to_many(relation, parent_primary_key_values, target_primary_key_values, context)
  end

  { content: nil, status: 204 }
end

#setup_routesObject



12
13
14
15
16
17
18
19
20
21
# File 'lib/forest_admin_agent/routes/resources/related/associate_related.rb', line 12

def setup_routes
  add_route(
    'forest_related_associate',
    'post',
    '/:collection_name/:id/relationships/:relation_name',
    ->(args) { handle_request(args) }
  )

  self
end