54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
# File 'lib/rails_relations_fix/counter_cache.rb', line 54
def add_counter_cache_callbacks(reflection)
cache_column = reflection.counter_cache_column
method_name = "belongs_to_counter_cache_after_add_for_#{reflection.name}".to_sym
define_method(method_name) do
association = send(reflection.name).reload rescue nil
if send("#{reflection.primary_key_name}_changed?") && send("#{reflection.primary_key_name}_change") != send("#{reflection.primary_key_name}_change").compact
association.class.increment_counter(cache_column, association.id) unless association.nil?
end
end
after_add(method_name)
method_name = "belongs_to_counter_cache_before_remove_for_#{reflection.name}".to_sym
define_method(method_name) do
association = send(reflection.name)
association.class.decrement_counter(cache_column, association.id) unless association.nil?
end
before_remove(method_name)
module_eval(
"#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)"
)
end
|