Module: ActsAsOrderedTree::Adapters::PostgreSQLAdapter

Defined in:
lib/acts_as_ordered_tree/adapters/postgresql_adapter.rb

Defined Under Namespace

Modules: Rails30UpdateAllPatch

Instance Method Summary collapse

Instance Method Details

#ancestorsObject

Recursive ancestors fetcher



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/acts_as_ordered_tree/adapters/postgresql_adapter.rb', line 29

def ancestors
  query = <<-QUERY
    SELECT id, #{parent_column}, 1 AS _depth
    FROM #{self.class.quoted_table_name}
    WHERE #{arel[:id].eq(parent.try(:id)).to_sql}
    UNION ALL
    SELECT alias1.id, alias1.#{parent_column}, _depth + 1
    FROM #{self.class.quoted_table_name} alias1
      INNER JOIN ancestors ON alias1.id = ancestors.#{parent_column}
  QUERY

  with_recursive_join(query, 'ancestors').
      order('ancestors._depth DESC').
      extending(Arrangeable)
end

#descendantsObject



65
66
67
# File 'lib/acts_as_ordered_tree/adapters/postgresql_adapter.rb', line 65

def descendants
  self_and_descendants.where(arel[:id].not_eq(id))
end

#rootObject



45
46
47
# File 'lib/acts_as_ordered_tree/adapters/postgresql_adapter.rb', line 45

def root
  root? ? self : ancestors.first
end

#self_and_ancestorsObject

Recursive ancestors fetcher



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/acts_as_ordered_tree/adapters/postgresql_adapter.rb', line 8

def self_and_ancestors
  if persisted? && !send("#{parent_column}_changed?")
    query = <<-QUERY
      SELECT id, #{parent_column}, 1 AS _depth
      FROM #{self.class.quoted_table_name}
      WHERE #{arel[:id].eq(id).to_sql}
      UNION ALL
      SELECT alias1.id, alias1.#{parent_column}, _depth + 1
      FROM #{self.class.quoted_table_name} alias1
        INNER JOIN self_and_ancestors ON alias1.id = self_and_ancestors.#{parent_column}
    QUERY

    with_recursive_join(query, 'self_and_ancestors').
        order('self_and_ancestors._depth DESC').
        extending(Arrangeable)
  else
    (ancestors + [self]).tap { |ary| ary.extend(Arrangeable) }
  end
end

#self_and_descendantsObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/acts_as_ordered_tree/adapters/postgresql_adapter.rb', line 49

def self_and_descendants
  query = <<-QUERY
    SELECT id, #{parent_column}, ARRAY[#{position_column}] AS _positions
    FROM #{self.class.quoted_table_name}
    WHERE #{arel[:id].eq(id).to_sql}
    UNION ALL
    SELECT alias1.id, alias1.#{parent_column}, _positions || alias1.#{position_column}
    FROM descendants INNER JOIN
      #{self.class.quoted_table_name} alias1 ON alias1.parent_id = descendants.id
  QUERY

  with_recursive_join(query, 'descendants').
      order('descendants._positions ASC').
      extending(Arrangeable)
end