Skip to content

Instantly share code, notes, and snippets.

@dfurber
Created April 19, 2012 18:20
Show Gist options
  • Save dfurber/2422783 to your computer and use it in GitHub Desktop.
Save dfurber/2422783 to your computer and use it in GitHub Desktop.
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