Skip to content

Instantly share code, notes, and snippets.

@tlowrimore
Last active January 13, 2023 21:12
Show Gist options
  • Save tlowrimore/5162327 to your computer and use it in GitHub Desktop.
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.
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
@ceskmcfran
Copy link

ceskmcfran commented Aug 1, 2017

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})"

  1. Is this secure against XSS or SQLi?
  2. I'm new with ruby on rails. Can you use
    where('? IN (?)', id_column, sub_query)
    instead of
    where "#{id_column} IN (#{sub_query})

Cheers

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