Skip to content

Instantly share code, notes, and snippets.

@acook
Created February 5, 2014 20:07
Show Gist options
  • Save acook/8831979 to your computer and use it in GitHub Desktop.
Save acook/8831979 to your computer and use it in GitHub Desktop.
# 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