module OnForm::Saving

Public Class Methods

included(base) click to toggle source
# File lib/on_form/saving.rb, line 3
def self.included(base)
  base.define_model_callbacks :save
end

Public Instance Methods

save(validate: true) click to toggle source
# File lib/on_form/saving.rb, line 42
def save(validate: true)
  save!(validate: validate)
rescue ActiveRecord::RecordInvalid, ActiveModel::ValidationError
  false
end
save!(validate: true) click to toggle source
# File lib/on_form/saving.rb, line 17
def save!(validate: true)
  transaction do
    reset_errors

    if validate
      run_validations!

      if !errors.empty?
        if form_errors?
          raise ActiveModel::ValidationError, self
        else
          raise ActiveRecord::RecordInvalid, self
        end
      end
    end

    run_callbacks :save do
      # we pass (validate: false) to avoid running the validations a second time, but we use save! to get the RecordNotFound behavior
      backing_model_instances.each { |backing_model| backing_model.save!(validate: false) }
      save_child_forms(validate: false)
    end
  end
  true
end
transaction(&block) click to toggle source
# File lib/on_form/saving.rb, line 7
def transaction(&block)
  backing_models = backing_model_instances

  if backing_models.empty?
    with_transactions([ActiveRecord::Base], &block)
  else
    with_transactions(backing_model_instances, &block)
  end
end
update(attributes) click to toggle source
# File lib/on_form/saving.rb, line 48
def update(attributes)
  transaction do
    self.attributes = attributes
    save
  end
end
Also aliased as: update_attributes
update!(attributes) click to toggle source
# File lib/on_form/saving.rb, line 55
def update!(attributes)
  transaction do
    self.attributes = attributes
    save!
  end
end
Also aliased as: update_attributes!
update_attributes(attributes)
Alias for: update
update_attributes!(attributes)
Alias for: update!

Private Instance Methods

save_child_forms(validate: true) click to toggle source
# File lib/on_form/saving.rb, line 76
def save_child_forms(validate: true)
  collection_wrappers.each_value {|collection| collection.save_forms(validate: validate) }
end
with_transactions(models, &block) click to toggle source
# File lib/on_form/saving.rb, line 66
def with_transactions(models, &block)
  if models.empty?
    block.call
  else
    models.shift.transaction do
      with_transactions(models, &block)
    end
  end
end