Class: ActiveRecord::UnionRelation::Subquery

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/union_relation.rb

Overview

This represents a combination of an ActiveRecord::Relation and a set of columns that it will pull.

Defined Under Namespace

Classes: MultiModelName, SingleModelName

Constant Summary collapse

NULL =

Sometimes you need some columns in some subqeries that you don’t need in others. In order to accomplish that and still maintain the matching number of columns, you can put a null in space of a column instead.

Arel.sql("NULL")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(relation, sources) ⇒ Subquery

Returns a new instance of Subquery.



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/active_record/union_relation.rb', line 78

def initialize(relation, sources)
  @relation = relation

  model = relation.model
  @model_name =
    if model._has_attribute?(model.inheritance_column)
      MultiModelName.new(
        quote_column_name(model.inheritance_column),
        model.descendants.map(&:name)
      )
    else
      SingleModelName.new(model.name)
    end

  @sources = sources.map { |source| source ? source.to_s : NULL }
end

Instance Attribute Details

#model_nameObject (readonly)

Returns the value of attribute model_name.



76
77
78
# File 'lib/active_record/union_relation.rb', line 76

def model_name
  @model_name
end

#relationObject (readonly)

Returns the value of attribute relation.



76
77
78
# File 'lib/active_record/union_relation.rb', line 76

def relation
  @relation
end

#sourcesObject (readonly)

Returns the value of attribute sources.



76
77
78
# File 'lib/active_record/union_relation.rb', line 76

def sources
  @sources
end

Instance Method Details

#merge_mappings(mappings, columns) ⇒ Object



106
107
108
109
110
111
# File 'lib/active_record/union_relation.rb', line 106

def merge_mappings(mappings, columns)
  # Remove the scope_name/table_name when using table_name.column
  mapping =
    columns.zip(sources.map { |source| source.split(".").last }).to_h
  model_name.each_name { |name| mappings[name] = mapping }
end

#to_arel(columns, discriminator) ⇒ Object



95
96
97
98
99
100
101
102
103
104
# File 'lib/active_record/union_relation.rb', line 95

def to_arel(columns, discriminator)
  relation.select(
    model_name.to_sql.as(quote_column_name(discriminator)),
    *sources
      .zip(columns)
      .map do |(source, column)|
        Arel.sql(source.to_s).as(quote_column_name(column))
      end
  ).arel
end