Module: ActiveRecord::JsonApiUpdate::Extensions

Defined in:
lib/activerecord/jsonapi_update/extensions.rb

Overview

Extensions included in ActiveRecord::Base to provide the new jsonapi methods

Instance Method Summary collapse

Instance Method Details

#assign_jsonapi_attributes(attributes) ⇒ void

This method returns an undefined value.

Assigns attributes to a model (but does not save it), generating the necessary destroy objects to remove any items not explicitly mentioned in any of the relationships that appear in attributes

Parameters:

  • attributes (Hash)

    A hash of attributes to save on the model and its associations



56
57
58
# File 'lib/activerecord/jsonapi_update/extensions.rb', line 56

def assign_jsonapi_attributes(attributes)
  assign_attributes(sanitize_jsonapi_attributes(attributes))
end

#jsonapi_update(attributes) ⇒ Boolean

Updates the model using the provided attributes in a manner that is consistent with a JSON API update.

In particular:

> Any or all of a resource’s relationships MAY be included in the resource object included in a PATCH > request. > > If a request does not include all of the relationships for a resource, the server MUST interpret the > missing relationships as if they were included with their current values. It MUST NOT interpret them > as null or empty values.

> If a relationship is provided in the relationships member of a resource object in a PATCH request, > its value MUST be a relationship object with a data member. The relationship’s value will be replaced > with the value specified in this member.

To accommodate this, nested hashes or arrays with the *_attributes suffix are processed as follows:

For hashes that have no id value, a new record is created (matching the behaviour of the normal #update method).

For hashes that have an id value, a find-and-update operation will occur (again, matching #update)

Any existing associated records not mentioned in the *_attributes hash or array will be destroyed (which is not how the normal #update method functions.)

Parameters:

  • attributes (Hash)

    A hash of attributes to save on the model and its associations

Returns:

  • (Boolean)

    True if the record successfully updated

See Also:



36
37
38
39
# File 'lib/activerecord/jsonapi_update/extensions.rb', line 36

def jsonapi_update(attributes)
  assign_jsonapi_attributes(attributes)
  save
end

#jsonapi_update!(attributes) ⇒ Boolean

Performs a JSON API compliant update on the model, throwing an exception if it fails

Parameters:

  • attributes (Hash)

    A hash of attributes to save on the model and its associations

Returns:

  • (Boolean)

    True if the record successfully updated

Raises:

  • (ActiveRecord::RecordNotSaved)

    If the record was not updated

See Also:

  • #json_api_update


46
47
48
49
# File 'lib/activerecord/jsonapi_update/extensions.rb', line 46

def jsonapi_update!(attributes)
  assign_jsonapi_attributes(attributes)
  save!
end