Skip to content

Instantly share code, notes, and snippets.

@renz45
Created October 15, 2011 03:14
Show Gist options
  • Save renz45/1288965 to your computer and use it in GitHub Desktop.
Save renz45/1288965 to your computer and use it in GitHub Desktop.
after_initialize :init_many_to_many_counters
def init_many_to_many_counters
setup_many_to_many_counts(:categories, :tags)
end
def setup_many_to_many_counts(args = {})
args.each do |k,v|
v = "#{self.class.downcase.pluralize}_count" if v.nil?
self.class_eval{
define_method "#{k}_with_count=" do |items|
has_many_items = self.method(k).call().dup
self.method(k).call(items)
has_many_update_counters(k, v, has_many_items)
end
}
end
end
def has_many_update_counters(table,col,items)
self_items = self.method(table).call()
binding.pry
unless(items == self_items)
model = table.to_s.singularize.camelize.constantize
decrement_arr = items - self_items
increment_arr = self_items - items
model.decrement_counter(col, decrement_arr.map{|d| d.id})
model.increment_counter(col, increment_arr.map{|i| i.id})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment