Method: Effective::CrudController::Save#save_resource

Defined in:
app/controllers/concerns/effective/crud_controller/save.rb

#save_resource(resource, action = :save, &block) ⇒ Object

This calls the appropriate member action, probably save!, on the resource.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'app/controllers/concerns/effective/crud_controller/save.rb', line 21

def save_resource(resource, action = :save, &block)
  save_action = ([:create, :update].include?(action) ? :save : action)
  raise "expected @#{resource_name} to respond to #{save_action}!" unless resource.respond_to?("#{save_action}!")

  if respond_to?(:current_user) && resource.respond_to?(:current_user=)
    resource.current_user ||= current_user
  end

  success = false
  exception = nil

  begin
    ActiveRecord::Base.transaction do
      EffectiveResources.transaction(resource) do
        run_callbacks(:resource_before_save)

        if resource.public_send("#{save_action}!") == false
          raise Effective::ActionFailed.new("failed to #{action}")
        end

        yield if block_given?

        run_callbacks(:resource_after_save)

        success = true
      rescue Effective::ActionFailed => e
        exception = e   # Dont rollback
      end
    end
  rescue ActiveRecord::RecordInvalid => e
    exception = e
  rescue => e
    exception = e
    notify_exception(e, resource, action) unless e.class.name == 'RuntimeError'
  end

  if exception.present?
    Rails.logger.info "  \e[31m\e[1mFAILED\e[0m\e[22m" # bold red
    Rails.logger.info "  Unable to #{action} #{resource} - #{exception.class} #{exception}"
    exception.backtrace.first(5).each { |line| Rails.logger.info('  ' + line) }

    if resource.respond_to?(:restore_attributes) && resource.persisted?
      resource.restore_attributes(['status', 'state'])
    end

    flash.now[:danger] = resource_flash(:danger, resource, action, e: exception)

    if exception.kind_of?(ActiveRecord::StaleObjectError)
      flash.now[:danger] = "#{flash.now[:danger]} <a href='#', class='alert-link' onclick='window.location.reload(true); return false;'>reload page and try again</a>"
    end
  end

  run_callbacks(success ? :resource_after_commit : :resource_error)

  success
end