Fix compatible issues with trashable and counter_cache

This commit is contained in:
Rei
2014-07-12 12:59:30 +08:00
parent eac0d9a485
commit fb11353b3a
3 changed files with 42 additions and 32 deletions

View File

@@ -11,21 +11,7 @@ class Comment < ActiveRecord::Base
validates :commentable, :user, presence: true
validates :body, presence: true
after_trash :decrement_counter_cache, :delete_all_notifications
after_restore :increment_counter_cache
after_destroy :increment_counter_cache, if: :trashed?
def increment_counter_cache
if commentable.has_attribute? :comments_count
commentable.class.update_counters commentable.id, comments_count: 1
end
end
def decrement_counter_cache
if commentable.has_attribute? :comments_count
commentable.class.update_counters commentable.id, comments_count: -1
end
end
after_trash :delete_all_notifications
def delete_all_notifications
notifications.delete_all

View File

@@ -7,6 +7,47 @@ module Trashable
scope :with_trashed, -> { unscope(where: :trashed) }
define_model_callbacks :trash, :restore
class << self
alias_method_chain :belongs_to, :trashable
end
end
module ClassMethods
def belongs_to_with_trashable(name, scope = nil, options = {})
belongs_to_without_trashable(name, scope, options)
reflection = reflections[name]
if reflection.options[:counter_cache]
after_restore lambda { |record|
record.belongs_to_counter_cache_after_create(reflection)
}
before_trash lambda { |record|
record.belongs_to_counter_cache_before_destroy(reflection)
}
end
return if method_defined? :belongs_to_counter_cache_before_destroy_with_trashable
class_eval do
def belongs_to_counter_cache_before_destroy_with_trashable(reflection)
unless trashed?
belongs_to_counter_cache_before_destroy_without_trashable(reflection)
end
end
def belongs_to_counter_cache_after_update_with_trashable(reflection)
unless trashed?
belongs_to_counter_cache_after_update_without_trashable(reflection)
end
end
end
alias_method_chain :belongs_to_counter_cache_before_destroy, :trashable
alias_method_chain :belongs_to_counter_cache_after_update, :trashable
end
end
def trash

View File

@@ -14,23 +14,6 @@ class Topic < ActiveRecord::Base
after_create :update_hot, :owner_subscribe
after_touch :update_hot
after_trash :decrement_counter_cache
after_restore :increment_counter_cache
# Fix double desc counter
after_destroy :increment_counter_cache, if: :trashed?
def increment_counter_cache
if category
Category.update_counters category.id, topics_count: 1
end
end
def decrement_counter_cache
if category
Category.update_counters category.id, topics_count: -1
end
end
def calculate_hot
order = Math.log10([comments_count, 1].max)
order + created_at.to_f / 45000