Class: ActiveRecord::UnionRelation

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

Defined Under Namespace

Classes: Error, MismatchedColumnsError, NoConfiguredSubqueriesError, Subquery

Constant Summary collapse

VERSION =
"0.3.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(columns, discriminator) ⇒ UnionRelation

Returns a new instance of UnionRelation.



122
123
124
125
126
# File 'lib/active_record/union_relation.rb', line 122

def initialize(columns, discriminator)
  @columns = columns.map(&:to_s)
  @discriminator = discriminator
  @subqueries = []
end

Instance Attribute Details

#columnsObject (readonly)

Returns the value of attribute columns.



120
121
122
# File 'lib/active_record/union_relation.rb', line 120

def columns
  @columns
end

#discriminatorObject (readonly)

Returns the value of attribute discriminator.



120
121
122
# File 'lib/active_record/union_relation.rb', line 120

def discriminator
  @discriminator
end

#subqueriesObject (readonly)

Returns the value of attribute subqueries.



120
121
122
# File 'lib/active_record/union_relation.rb', line 120

def subqueries
  @subqueries
end

Instance Method Details

#add(relation, *sources) ⇒ Object

Adds a subquery to the overall union.



129
130
131
132
133
134
135
# File 'lib/active_record/union_relation.rb', line 129

def add(relation, *sources)
  if columns.length != sources.length
    raise MismatchedColumnsError.new(columns, sources)
  end

  subqueries << Subquery.new(relation, sources)
end

#allObject

Creates an ActiveRecord::Relation object that will pull all of the subqueries together.



139
140
141
142
143
144
# File 'lib/active_record/union_relation.rb', line 139

def all
  raise NoConfiguredSubqueriesError if subqueries.empty?

  model = subqueries.first.relation.model
  subclass_for(model).from(union_for(model)).select(discriminator, *columns)
end