Skip to content

ChangeSets and Dirty Tracking

James R. Griffin III edited this page Oct 25, 2017 · 12 revisions

When making changes to a Valkyrie resource, use a ChangeSet and ChangeSetPersister. Validate the properties through the changeset, sync the changeset to the model, then save the changes through the ChangeSetPersister. Please note that models, by default, can be persisted with invalid data using ChangeSetPersisters. Should it be the case that a client must absolutely must avoid persisting model properties with invalid data, the property definitions themselves can be strictly typed.

For more general info on change tracking, see Reform's dirty tracking documentation.

Examples

Entirely changing a property

change_set = MyChangeSet.new(resource)
change_set.validate(page_number: 12)

# Some examples of ways to see that this has changed:
# change_set.changed? # => true
# change_set.changed # => {"page_number" => true}
# change_set.changed["page_number"] # => true

# Sets the value on the model
change_set.sync

# Saves the data
change_set_persister = ChangeSetPersister.new(
  metadata_adapter: Valkyrie.config.metadata_adapter,
  storage_adapter: Valkyrie.config.storage_adapter
)
updated_resource = change_set_persister.save(change_set: change_set)

Incrementally changing a property

change_set = MyChangeSet.new(resource)
change_set.member_ids << '1'
# optional, if you know the field doesn't need to be validated
change_set.validate(member_ids: change_set.member_ids)
change_set.sync

change_set_persister = ChangeSetPersister.new(
  metadata_adapter: Valkyrie.config.metadata_adapter,
  storage_adapter: Valkyrie.config.storage_adapter
)
updated_resource = change_set_persister.save(change_set: change_set)