Module: ActiveRecordCompose::Persistence

Extended by:
ActiveSupport::Concern
Includes:
Callbacks
Included in:
Model
Defined in:
lib/active_record_compose/persistence.rb

Instance Method Summary collapse

Methods included from Callbacks

after_create, after_save, after_update, around_create, around_save, around_update, before_create, before_save, before_update

Instance Method Details

#save(**options) ⇒ Boolean

Save the models that exist in models. Returns false if any of the targets fail, true if all succeed.

The save is performed within a single transaction.

Only the :validate option takes effect as it is required internally. However, we do not recommend explicitly specifying validate: false to skip validation. Additionally, the :context option is not accepted. The need for such a value indicates that operations from multiple contexts are being processed. If the contexts differ, we recommend separating them into different model definitions.

Parameters:

  • options (Hash)

    parameters.

Options Hash (**options):

  • :validate (Boolean)

    Whether to run validations. This option is intended for internal use only. Users should avoid explicitly passing validate: false, as skipping validations can lead to unexpected behavior.

Returns:

  • (Boolean)

    returns true on success, false on failure.



30
31
32
33
34
# File 'lib/active_record_compose/persistence.rb', line 30

def save(**options)
  with_callbacks { save_models(**options, bang: false) }
rescue ActiveRecord::RecordInvalid
  false
end

#save!(**options) ⇒ void

Behavior is same to #save, but raises an exception prematurely on failure.

Raises:

  • ActiveRecord::RecordInvalid

  • ActiveRecord::RecordNotSaved

See Also:



41
42
43
# File 'lib/active_record_compose/persistence.rb', line 41

def save!(**options)
  with_callbacks { save_models(**options, bang: true) } || raise_on_save_error
end

#update(attributes) ⇒ Boolean

Assign attributes and #save.

Parameters:

  • attributes (Hash<String, Object>)

    new attributes.

Returns:

  • (Boolean)

    returns true on success, false on failure.

See Also:



51
52
53
54
# File 'lib/active_record_compose/persistence.rb', line 51

def update(attributes)
  assign_attributes(attributes)
  save
end

#update!(attributes) ⇒ void

Behavior is same to #update, but raises an exception prematurely on failure.

Parameters:

  • attributes (Hash<String, Object>)

    new attributes.

Raises:

  • ActiveRecord::RecordInvalid

  • ActiveRecord::RecordNotSaved

See Also:



64
65
66
67
# File 'lib/active_record_compose/persistence.rb', line 64

def update!(attributes)
  assign_attributes(attributes)
  save!
end