Skip to content

Commit

Permalink
ActiveRecord::Relation unions [PROPOSAL], closes rails#939
Browse files Browse the repository at this point in the history
Depends on rails/arel#118.
The accepted implementation could act as
a unions list, or a new top-level object,
which would change this patch proposal.
  • Loading branch information
Olivier Favre committed Aug 3, 2012
1 parent 01b470f commit 29b8ebd
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion activerecord/lib/active_record/relation/query_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ module QueryMethods
extend ActiveSupport::Concern

attr_accessor :includes_values, :eager_load_values, :preload_values,
:select_values, :group_values, :order_values, :joins_values,
:select_values, :group_values, :order_values, :joins_values, :unions_values,
:where_values, :having_values, :bind_values,
:limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value,
:from_value, :reordering_value, :reverse_order_value,
Expand Down Expand Up @@ -123,6 +123,17 @@ def joins(*args)
relation
end

def union(*args)
return self if args.compact.blank?

relation = clone

relation.unions_values ||= []
relation.unions_values += args

relation
end

def bind(value)
relation = clone
relation.bind_values += [value]
Expand Down Expand Up @@ -284,6 +295,8 @@ def build_arel
arel.from(@from_value) if @from_value
arel.lock(@lock_value) if @lock_value

build_union(arel, @unions_values) unless @unions_values.empty?

arel
end

Expand Down Expand Up @@ -375,6 +388,10 @@ def build_joins(manager, joins)
manager
end

def build_union(arel, unions)
arel.union(*unions.map {|union| union.build_arel})
end

def build_select(arel, selects)
unless selects.empty?
@implicit_readonly = false
Expand Down

2 comments on commit 29b8ebd

@ablignaut
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Olivier
Is anything happening to these code changes?
Are you going to pull request this?
Regards,
Andrew

@ofavre
Copy link

@ofavre ofavre commented on 29b8ebd Feb 26, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rails/arel#118 needs to be merged first.
As @jroes just decided to let me drive it, I'll compare my solution to his and come up with a workable pull request.
Once merged, I could then adapt this patch and pull request it.
I'll commit my proposal "as is" (NoWarranty™) so you can build upon it, or drive these issues as I'm not sure of the time I can put on these.

Please sign in to comment.