Skip to content

Instantly share code, notes, and snippets.

@claptimes5
Forked from lsiden/gist:260167a4d3574a580d97
Last active August 29, 2015 14:05
Show Gist options
  • Save claptimes5/5d764f04097140afaa9e to your computer and use it in GitHub Desktop.
Save claptimes5/5d764f04097140afaa9e to your computer and use it in GitHub Desktop.
#http://stackoverflow.com/a/15413611/270511
module Unionable
extend ActiveSupport::Concern
module ClassMethods
def union_scope(*scopes)
id_column = "#{table_name}.id"
if (sub_query = scopes.reject { |sc| sc.count == 0 }.map { |s| s.select(id_column).to_sql }.join(" UNION ")).present?
where "#{id_column} IN (#{sub_query})"
else
none
end
end
end
end
@claptimes5
Copy link
Author

Updated to use ActiveSupport::Concern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment