her icon indicating copy to clipboard operation
her copied to clipboard

missing callback if error returned

Open noctivityinc opened this issue 7 years ago • 2 comments

Right now the after_save and other related callbacks are cancelled if an error is returned. This creates an issue if we are trying to catch these situations and act on them in our models.

For example, I'd like to call this after attempting to save in Rails 5:

 def check_for_errors
    if self.response_errors.any?
      self.response_errors.each do |attribute, errors|
        errors.each do |error|
          self.errors.add(attribute, error)
        end
      end
    end
  end

to convert the response_errors into Rails errors but cannot because of this issue.

noctivityinc avatar Oct 19 '18 00:10 noctivityinc

For anyone else curious, I'm overriding the save method based on a method provided in #178 using a concern:

module Her
  module Overridable
    extend ActiveSupport::Concern

    def save
      callback = new? ? :create : :update
      method = self.class.method_for(callback)

      run_callbacks :save do
        run_callbacks callback do
          self.class.request(to_params.merge(:_method => method, :_path => request_path)) do |parsed_data, response|
            load_from_parsed_data(parsed_data)
            add_errors_to_base if @response_errors.any?

            return false if !response.success? || @response_errors.any?
            changes_applied
          end
        end
      end

      self
    end

    private

    def add_errors_to_base
      @response_errors.each do |attr, messages|
        [*messages].map { |msg| self.errors.add(attr, msg) }
      end
    end
  end
end

which is placed in concerns/her/overridable.rb and calling it in my models like such:

class Site
  include Her::Model
  include Her::Overridable

Not the best solution since it will break if the save method changes, but it does work.

noctivityinc avatar Oct 19 '18 00:10 noctivityinc

You could try following #101 and see if that helps. The method's been renamed as store_response_errors

zacharywelch avatar Feb 14 '19 15:02 zacharywelch