Skip to content

Instantly share code, notes, and snippets.

@m4tm4t
Created June 18, 2012 15:48
Show Gist options
  • Save m4tm4t/2949029 to your computer and use it in GitHub Desktop.
Save m4tm4t/2949029 to your computer and use it in GitHub Desktop.
Update counters monkey patch when an association get updated
module FixUpdateCounters
def fix_updated_counters
self.changes.each {|key, value|
# key should match /master_files_id/ or /bibls_id/
# value should be an array ['old value', 'new value']
if key =~ /_id/
changed_class = key.sub(/_id/, '')
# Get real class of changed attribute, so work both with namespaced/normal models
klass = self.association(changed_class.to_sym).klass
# Namespaced model return a slash, split it.
unless (counter_name = "#{self.class.name.underscore.pluralize.split("/")[1]}_count".to_sym)
counter_name = "#{self.class.name.underscore.pluralize}_count".to_sym
end
klass.decrement_counter(counter_name, value[0]) unless value[0] == nil
klass.increment_counter(counter_name, value[1]) unless value[1] == nil
end
}
end
end
ActiveRecord::Base.send(:include, FixUpdateCounters)
class (Namespaced::)Model < ActiveRecord::Base
belongs_to :association, counter_cache: true
after_update :fix_updated_counters
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment