Created
February 5, 2014 20:07
-
-
Save acook/8831979 to your computer and use it in GitHub Desktop.
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
# Create UNION qeuries between ActiveRecord 3.x Relation objects. | |
# inspired by: https://coderwall.com/p/9hohaa | |
module Union | |
def union *relations | |
opts = relations.extract_options! | |
model = ((is_a?(ActiveRecord::Base) || is_a?(ActiveRecord::Relation)) && self) || relations.first.klass | |
query = 'SELECT' | |
query << ' DISTINCT' if opts[:distinct] | |
query << ' * FROM ((' | |
query << relations.map { |r| r.ast.to_sql }.join(') UNION (') | |
query << ')) AS t' | |
query << " ORDER BY #{opts[:order]}" if opts[:order] | |
query << " LIMIT #{opts[:limit]}" if opts[:limit] | |
model.find_by_sql query | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment