Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created October 13, 2019 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgaskins/baafc9484b5cba1e6ee2be3d9eba409a to your computer and use it in GitHub Desktop.
Save jgaskins/baafc9484b5cba1e6ee2be3d9eba409a to your computer and use it in GitHub Desktop.
SQL result set operations for ActiveRecord
module SetOperations
def union_scope(*scopes)
apply_operation :UNION, scopes
end
def intersect_scope(*scopes)
apply_operation :INTERSECT, scopes
end
def except_scope(*scopes)
apply_operation :EXCEPT, scopes
end
private
def apply_operation(operation, scopes)
id_column = "#{table_name}.#{primary_key}"
sub_query =
scopes
.map { |s| s.select(id_column).to_sql }
.join(" #{operation} ")
where "#{id_column} IN (#{sub_query})"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment