Skip to content

Instantly share code, notes, and snippets.

@pdswan
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdswan/0c51b7194cbc3ddb7f82 to your computer and use it in GitHub Desktop.
Save pdswan/0c51b7194cbc3ddb7f82 to your computer and use it in GitHub Desktop.
An Unsanctioned Union
module ActiveRecordScopeExtensions
def self.union(left, right)
active_record_klass = left.klass
arel_union = [left, right].map do |scope|
scope.select("#{active_record_klass.table_name}.id")
end.reduce(&:union)
temporary_table_name = TemporaryTableName.new([active_record_klass.table_name, "union"].join("_")).to_s
active_record_klass.joins("INNER JOIN (#{arel_union.to_sql}) as #{temporary_table_name} ON #{temporary_table_name}.id = #{active_record_klass.table_name}.id")
end
class TemporaryTableName
def initialize(prefix, random = SecureRandom.hex)
@prefix = prefix
@random = random
end
def to_s
[prefix, random].join("_")
end
private
attr_reader :random, :prefix
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment