Last active
March 30, 2025 21:26
-
-
Save tlowrimore/5162327 to your computer and use it in GitHub Desktop.
Unions multiple scopes on a model, and returns an instance of ActiveRecord::Relation.
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::UnionScope | |
def self.included(base) | |
base.send :extend, ClassMethods | |
end | |
module ClassMethods | |
def union_scope(*scopes) | |
id_column = "#{table_name}.#{primary_key}" | |
sub_query = scopes.map { |s| s.select(id_column).to_sql }.join(" UNION ") | |
where "#{id_column} IN (#{sub_query})" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
id_column = "#{table_name}.#{primary_key}"
sub_query = scopes.map { |s| s.select(id_column).to_sql }.join(" UNION ")
where "#{id_column} IN (#{sub_query})"
where('? IN (?)', id_column, sub_query)
instead of
where "#{id_column} IN (#{sub_query})
Cheers