Created
October 15, 2011 03:14
-
-
Save renz45/1288965 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
after_initialize :init_many_to_many_counters | |
def init_many_to_many_counters | |
setup_many_to_many_counts(:categories, :tags) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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