Skip to content

Commit

Permalink
Merge pull request #451 from seuros/dgilperez-counter_cache
Browse files Browse the repository at this point in the history
[Fix] counter_cache, Check for #390 to prevent application breakage.
  • Loading branch information
bf4 committed Jan 13, 2014
2 parents 8ee0a10 + 2c571fa commit f891175
Showing 1 changed file with 5 additions and 11 deletions.
16 changes: 5 additions & 11 deletions lib/acts_as_taggable_on/tagging.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,42 +9,36 @@ class Tagging < ::ActiveRecord::Base #:nodoc:
:tagger,
:tagger_type,
:tagger_id if defined?(ActiveModel::MassAssignmentSecurity)

belongs_to :tag, :class_name => 'ActsAsTaggableOn::Tag'
belongs_to :taggable, :polymorphic => true
belongs_to :tagger, :polymorphic => true

validates_presence_of :context
validates_presence_of :tag_id

validates_uniqueness_of :tag_id, :scope => [ :taggable_type, :taggable_id, :context, :tagger_id, :tagger_type ]
validates_uniqueness_of :tag_id, :scope => [:taggable_type, :taggable_id, :context, :tagger_id, :tagger_type]

after_destroy :remove_unused_tags

# Conditionally adds a counter cache when cache column is present.
# We just regenerate the association. It's the easiest way.
# We just regenerate the association. It's the easiest way.
# TODO: require the counter cache in release 4.0.0 and remove these methods
# @see :columns in ActsAsTaggableOn::Taggable::Cache
def self.columns
@acts_as_taggable_on_counter_columns ||= begin
db_columns = super
if _has_tags_counter_column?(db_columns)
belongs_to :tag, :class_name => 'ActsAsTaggableOn::Tag', :counter_cache => true
end
belongs_to :tag, :class_name => 'ActsAsTaggableOn::Tag', :counter_cache => ActsAsTaggableOn::Tag.column_names.include?('taggings_count')
db_columns
end
end

# @private
def self._has_tags_counter_column?(db_columns)
db_column_names = db_columns.map(&:name)
db_column_names.include?("taggings_count")
end


private

def remove_unused_tags
if ActsAsTaggableOn.remove_unused_tags
# TODO: use taggings_count in release 4.0.0
if tag.taggings.count.zero?
tag.destroy
end
Expand Down

0 comments on commit f891175

Please sign in to comment.