Skip to content

Instantly share code, notes, and snippets.

@corey
Forked from scttymn/gist:1283177
Created October 21, 2011 18:53
Show Gist options
  • Save corey/1304630 to your computer and use it in GitHub Desktop.
Save corey/1304630 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