-
-
Save napcs/298898 to your computer and use it in GitHub Desktop.
update_attributes fix for counter_cache
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 belongs_to(association_id, options = {}) | |
association_column = options[:foreign_key] ||= association_id.to_s + "_id" # | |
reflection = create_belongs_to_reflection(association_id, options) | |
if reflection.options[:polymorphic] | |
association_accessor_methods(reflection, BelongsToPolymorphicAssociation) | |
else | |
association_accessor_methods(reflection, BelongsToAssociation) | |
association_constructor_method(:build, reflection, BelongsToAssociation) | |
association_constructor_method(:create, reflection, BelongsToAssociation) | |
end | |
# This is the part i added | |
if options[:counter_cache] | |
define_method("#{association_column}=") do |*params| | |
new_associated_id = params.first unless params.empty? | |
current_associated_id = self.send("#{association_column}") | |
reflection.class_name.constantize.update_counters current_associated_id, reflection.counter_cache_column.to_sym => -1 | |
reflection.class_name.constantize.update_counters new_associated_id, reflection.counter_cache_column.to_sym => +1 | |
self.attributes[association_column.to_sym] = new_associated_id | |
end | |
add_counter_cache_callbacks(reflection) | |
end | |
add_touch_callbacks(reflection, options[:touch]) if options[:touch] | |
configure_dependency_for_belongs_to(reflection) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment