class Tag < ActiveRecord::Base
  default_scope { order(name: :asc) }
  
  
	acts_as_tree  dependent: :nullify
	before_validation do
		self.slug = self.name.to_s.to_slug
		
	end
	

	attr_accessor :no_child_count
  
  
	has_many :tag_taggables, :dependent => :delete_all
	has_many :taggable, :through => :tag_taggables


  validates :slug, :presence => true, :uniqueness => true

  def self.tag_list
    r = []
    Tag.all.each do |tag|
      r << tag.name
    end
    r
    
  end
  
  after_save do 
    if !self.no_child_count
      self.no_child_count =  true
      self.update_child_count
    
      self.ancestors.each do |ancest|
        ancest.no_child_count =  true
        ancest.update_child_count
      
      end
    end
      
    
    
  end
  
  def update_child_count 
    
    self.child_count= self.children.count
    self.no_child_count =  true
    self.save
    
    
    
  end
  
  def self.update_child_counts
    Tag.all.each do |tag|
      tag.update_child_count
    end
    
  end
  
  
  
end
