Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Union Query in AR
module UnionQuery
extend ActiveSupport::Concern
included do
def self.union(query1, query2, params={}, type='all')
find_by_sql "#{query1.to_sql} UNION #{type} #{query2.to_sql}", params
end
def self.unite_with(query2)
union scoped, query2
end
end
end
class Thing1 < ActiveRecord::Base
scope :unite_me, lambda { select('name') }
include UnionQuery
end
class Thing2 < ActiveRecord::Base
scope :also_unite_me, lambda { select('name') }
end
Thing1.union(Thing1.unite_me, Thing2.also_unite_me)
Thing2.select('name').unite_with Thing2.select('name')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment