Class: JsonapiCompliable::Util::Persistence Private

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi_compliable/util/persistence.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Save the given Resource#model, and all of its nested relationships.

Instance Method Summary collapse

Constructor Details

#initialize(resource, meta, attributes, relationships, caller_model) ⇒ Persistence

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Persistence

Parameters:

  • resource (Resource)

    the resource instance

  • meta (Hash)

    see (Deserializer#meta)

  • attributes (Hash)

    see (Deserializer#attributes)

  • relationships (Hash)

    see (Deserializer#relationships)



8
9
10
11
12
13
14
# File 'lib/jsonapi_compliable/util/persistence.rb', line 8

def initialize(resource, meta, attributes, relationships, caller_model)
  @resource      = resource
  @meta          = meta
  @attributes    = attributes
  @relationships = relationships
  @caller_model  = caller_model
end

Instance Method Details

#runObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Perform the actual save logic.

belongs_to must be processed before/separately from has_many - we need to know the primary key value of the parent before persisting the child.

Flow:

  • process parents

  • update attributes to reflect parent primary keys

  • persist current object

  • associate temp id with current object

  • associate parent objects with current object

  • process children

  • associate children

  • run post-process sideload hooks

  • return current object

Returns:

  • the persisted model instance



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/jsonapi_compliable/util/persistence.rb', line 34

def run
  parents = process_belongs_to(@relationships)
  update_foreign_key_for_parents(parents)

  persisted = persist_object(@meta[:method], @attributes)
  assign_temp_id(persisted, @meta[:temp_id])

  associate_parents(persisted, parents)

  children = process_has_many(@relationships, persisted) do |x|
    update_foreign_key(persisted, x[:attributes], x)
  end

  associate_children(persisted, children) unless @meta[:method] == :destroy
  post_process(persisted, parents)
  post_process(persisted, children)
  persisted
end