Module: Treeify::ClassMethods

Defined in:
lib/treeify.rb

Instance Method Summary collapse

Instance Method Details

#config(hash = {}) ⇒ Object



13
14
15
16
17
# File 'lib/treeify.rb', line 13

def config(hash = {})
  # apparently columns is a reserved word in rails
  self.cols       = hash[:cols]
  self.table_name = hash[:table_name]
end

#queryObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/treeify.rb', line 19

def query 
  "WITH RECURSIVE cte (id, #{self.cols.join(',')}, path, parent_id, depth)  AS (
     SELECT  id,
      #{self.cols.join(',')}
       array[id] AS path,
       parent_id,
       1 AS depth
     FROM    #{self.table_name}
     WHERE   parent_id IS NULL

     UNION ALL

     SELECT  #{self.table_name}.id,
        #{self.cols.map{ |c| self.table_name << '.' << c }.join(',')},
        #{self.table_name}.author,
        cte.path || #{self.table_name}.id,
        #{self.table_name}.parent_id,
        cte.depth + 1 AS depth
     FROM    #{self.table_name}
     JOIN cte ON #{self.table_name}.parent_id = cte.id
   )
   SELECT id, #{self.cols.join(',')}, path, depth FROM cte
   ORDER BY path;"
end