Skip to content

Instantly share code, notes, and snippets.

@napcs
Forked from eladmeidar/associations.rb
Created February 9, 2010 03:53
Show Gist options
  • Save napcs/298898 to your computer and use it in GitHub Desktop.
Save napcs/298898 to your computer and use it in GitHub Desktop.
update_attributes fix for counter_cache
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