Give an extension for your active record classes that allows union queries. The queries can be active record relations, scoping method names, or SQL strings so that you have some flexibility around how you write your queries.
Include in your project
gem "active_record_sql_unionizer"
gem install active_record_sql_unionizer
Bring ActiveRecordSqlUnionizer into your active record class.
class Dummy < ActiveRecord::Base
include ActiveRecordSqlUnionizer
def self.some_scoping_method
where(some: "stuff")
end
end
You are then free to call
sql_string = "SELECT * from dummies where some='thing'"
active_record_relation = Dummy.where(some: "other thing")
result = Dummy.unionize(sql_string, active_record_relation, :some_scoping_method)
The unionize
method takes any amount of ActiveRecord::Relation or valid SQL strings.
Currently just tested with postgres. Source 'TEST_DB' as the test database you want to use or create the test db in irb;
require 'pg'
conn = PG.connect(dbname: 'postgres')
conn.exec("CREATE DATABASE unionizer_test")