Module: Ooor::AutosaveAssociation

Extended by:
ActiveSupport::Concern
Included in:
Base
Defined in:
lib/ooor/autosave_association.rb

Overview

Ooor Autosave Association, adapted from ActiveRecord 4.1

AutosaveAssociation is a module that takes care of automatically saving associated records when their parent is saved. In addition to saving, it also destroys any associated records that were marked for destruction. (See mark_for_destruction and marked_for_destruction?).

Saving of the parent, its associations, and the destruction of marked associations, all happen inside a transaction. This should never leave the database in an inconsistent state.

If validations for any of the associations fail, their error messages will be applied to the parent (TODO)

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#changed_for_autosave?Boolean

Returns whether or not this record has been changed in any way (including whether any of its nested autosave associations are likewise changed)

Returns:

  • (Boolean)


118
119
120
# File 'lib/ooor/autosave_association.rb', line 118

def changed_for_autosave?
  new_record? || changed? || marked_for_destruction? # TODO || nested_records_changed_for_autosave?
end

#destroyed_by_associationObject

Returns the association for the parent being destroyed.

Used to avoid updating the counter cache unnecessarily.



112
113
114
# File 'lib/ooor/autosave_association.rb', line 112

def destroyed_by_association
  @destroyed_by_association
end

#destroyed_by_association=(reflection) ⇒ Object

Records the association that is being destroyed and destroying this record in the process.



105
106
107
# File 'lib/ooor/autosave_association.rb', line 105

def destroyed_by_association=(reflection)
  @destroyed_by_association = reflection
end

#mark_for_destructionObject

Marks this record to be destroyed as part of the parents save transaction. This does not actually destroy the record instantly, rather child record will be destroyed when parent.save is called.

Only useful if the :autosave option on the parent is enabled for this associated model.



92
93
94
# File 'lib/ooor/autosave_association.rb', line 92

def mark_for_destruction
  @marked_for_destruction = true
end

#marked_for_destruction?Boolean

Returns whether or not this record will be destroyed as part of the parents save transaction.

Only useful if the :autosave option on the parent is enabled for this associated model.

Returns:

  • (Boolean)


99
100
101
# File 'lib/ooor/autosave_association.rb', line 99

def marked_for_destruction?
  @marked_for_destruction
end

#reload(options = nil) ⇒ Object

Reloads the attributes of the object as usual and clears marked_for_destruction flag.



81
82
83
84
85
# File 'lib/ooor/autosave_association.rb', line 81

def reload(options = nil)
  @marked_for_destruction = false
  @destroyed_by_association = nil
  super
end