category.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. class Category < ActiveRecord::Base
  2. ##--- Associaciones
  3. has_and_belongs_to_many :products
  4. belongs_to :parent, :class_name => "Category"
  5. has_many :children, -> { where "status!= 0" }, :class_name => "Category", :foreign_key => 'parent_id'
  6. enum status: [ :erased, :active, :inactive ]
  7. ##--- Llevar registro de Actividad del usuario
  8. audited
  9. ##--- Validaciones previas de guardar
  10. validates :category , presence: { message: "Debe capturar el nombre de la línea de producto." }
  11. ##--- Tipo de vistas / consultas
  12. scope :vigentes, -> { where( "status != 0").order(" status ASC, category ASC") }
  13. scope :activos, -> { where( "status = 1").order(" category ASC") }
  14. scope :activos_padre, -> { where( "status = 1 AND parent_id = 0").order(" category ASC") }
  15. scope :get_parents, -> { where( "parent_id = 0 and status != 0").order(" category ASC") }
  16. def descendents
  17. self_and_descendents - [self]
  18. end
  19. def self_and_descendents
  20. self.class.tree_for(self)
  21. end
  22. def self.tree_for(instance)
  23. where("#{table_name}.id IN (#{tree_sql_for(instance)})").order("#{table_name}.id")
  24. end
  25. def self.tree_sql_for(instance)
  26. tree_sql = <<-SQL
  27. WITH RECURSIVE search_tree(id, path) AS (
  28. SELECT id, ARRAY[id]
  29. FROM #{table_name}
  30. WHERE id = #{instance.id}
  31. UNION ALL
  32. SELECT #{table_name}.id, path || #{table_name}.id
  33. FROM search_tree
  34. JOIN #{table_name} ON #{table_name}.parent_id = search_tree.id
  35. WHERE NOT #{table_name}.id = ANY(path)
  36. )
  37. SELECT id FROM search_tree ORDER BY path
  38. SQL
  39. end
  40. protected
  41. before_save do
  42. self.parent_id = 0 if parent_id.nil?
  43. end
  44. end