Created
March 10, 2016 17:41
-
-
Save tlowrimore/f0e3eca483395de3d373 to your computer and use it in GitHub Desktop.
Extends the functionality set forth in union_scope.rb, to include EXCEPT and INTERSECT operations
This file contains hidden or 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
module ActiveRecord | |
module Scopes | |
module SetOperations | |
extend ActiveSupport::Concern | |
class_methods do | |
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 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Less problems and easier to follow: