Skip to content

Instantly share code, notes, and snippets.

@scttymn
Created October 13, 2011 02:18
Show Gist options
  • Save scttymn/1283177 to your computer and use it in GitHub Desktop.
Save scttymn/1283177 to your computer and use it in GitHub Desktop.
Hack the counter_cache
# activerecord/lib/active_record/associations/builder/belongs_to.rb automagically creates
# the private methods for you if you include counter_cache in your belongs_to association.
# We simply override the basic behavior of these with our own conditions.
#
# For more information, check out:
# https://github.com/rails/rails/blob/733bfa63f5d8d3b963202b6d3e9f00b4db070b91/activerecord/lib/active_record/associations/builder/belongs_to.rb
# Lines 23 - 44
class Inventory < ActiveRecord::Base
belongs_to :user, counter_cache:true
def owned?
state == 1
end
private
def belongs_to_counter_cache_after_create_for_user
User.increment_counter("inventories_count", user.id) if self.owned?
end
def belongs_to_counter_cache_before_destroy_for_user
User.decrement_counter("inventories_count", user.id) if self.owned?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment