Module: PaperTrail::RelatedChanges::Hierarchy::Query

Defined in:
lib/paper_trail/related_changes/hierarchy/query.rb

Class Method Summary collapse

Class Method Details

.call(model, id) ⇒ Object

Builds a UNION joined set of queries that finds related versions to the 4th generation.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/paper_trail/related_changes/hierarchy/query.rb', line 4

def call(model, id)
  parent_query_r0 = parent(model.name, id)
  hierarchy       = PaperTrail::RelatedChanges::Hierarchy.model_type_children(model).each_with_object([]) do |(_n, r1), col|
    parent_query_r1 = call_query(parent_query_r0, r1)
    col << parent_query_r1
    PaperTrail::RelatedChanges::Hierarchy.model_type_children(r1.klass).each do |_n, r2|
      parent_query_r2 = call_query(parent_query_r1, r2)
      col << parent_query_r2
      PaperTrail::RelatedChanges::Hierarchy.model_type_children(r2.klass).each do |_n, r3|
        parent_query_r3 = call_query(parent_query_r2, r3)
        col << parent_query_r3
      end
    end
  end
  final           = [
    parent_query_r0,
    *hierarchy.uniq
  ].join("\nUNION\n")

  <<~SQL
    SELECT #{columns('hierarchy')},
      CASE event
      WHEN 'create' THEN 1
      WHEN 'update' THEN 2
      WHEN 'destroy' THEN 3
      ELSE 4 END as rank
    FROM (#{final}) hierarchy
  SQL
end