Created
April 19, 2012 18:20
-
-
Save dfurber/2422783 to your computer and use it in GitHub Desktop.
Union Query in AR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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