Skip to content

Instantly share code, notes, and snippets.

@bogdanRada
Forked from lsiden/gist:260167a4d3574a580d97
Last active February 7, 2018 17:56
Show Gist options
  • Save bogdanRada/c735c58be848c547f3620f8c788956a2 to your computer and use it in GitHub Desktop.
Save bogdanRada/c735c58be848c547f3620f8c788956a2 to your computer and use it in GitHub Desktop.
module ActiveRecord::UnionScope
#https://gist.github.com/tlowrimore/5162327
#http://stackoverflow.com/a/15413611/270511
module ActiveRecord::UnionScope
def self.included(base)
base.send :extend, ClassMethods
end
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
Rails::VERSION::MAJOR.to_i >= 4 ? self.none : self.scoped
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment