Module: MultipleTableInheritance::Parent::Relation

Defined in:
lib/multiple_table_inheritance/parent/relation.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
7
8
9
# File 'lib/multiple_table_inheritance/parent/relation.rb', line 4

def self.included(base)
  base.class_eval do
    attr_accessor :return_supertype
    alias_method_chain :to_a, :inherits
  end
end

Instance Method Details

#as_supertypeObject



41
42
43
44
45
# File 'lib/multiple_table_inheritance/parent/relation.rb', line 41

def as_supertype
  relation = clone
  relation.return_supertype = true
  relation
end

#to_a_with_inheritsObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/multiple_table_inheritance/parent/relation.rb', line 11

def to_a_with_inherits
  parent_records = to_a_without_inherits
  return parent_records if @return_supertype || !@klass.subtype_column
  
  # Find all child records.
  child_records = []
  ids_by_type(parent_records).each do |type, ids|
    begin
      klass = type.constantize
      child_records += klass.find(ids)
    rescue NameError => e
      logger.warn "Can't find matching child association for deletion: #{type} #{ids.inspect}" if logger
    end
  end
  
  # Associate the parent records with the child records to reduce SQL calls and prevent recursion.
  child_records.each do |child|
    association_name = @klass.to_s.demodulize.underscore
    parent = parent_records.find { |parent| child.id == parent.id }
    child.send("#{association_name}=", parent)
  end
  
  # Order the child_records array to match the order of the parent_records array.
  child_records.sort! do |a, b|
    a_index = parent_records.index { |parent| parent.id == a.id }
    b_index = parent_records.index { |parent| parent.id == b.id }
    a_index <=> b_index
  end
end