Skip to content

Instantly share code, notes, and snippets.

@renews
Created August 18, 2014 20:59
Show Gist options
  • Save renews/d8fd2211b07e4cc78501 to your computer and use it in GitHub Desktop.
Save renews/d8fd2211b07e4cc78501 to your computer and use it in GitHub Desktop.
Ability to use union on activerecord relations. Put: include ActiveRecord::UnionScope in the model.
module ActiveRecord
module UnionScope
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
none
end
end
end
end
ActiveRecord::Base.send(:extend, ActiveRecord::UnionScope)
@dmitry
Copy link

dmitry commented Dec 17, 2019

Less problems and easier to follow:

    def union_scope(*scopes)
      scopes.inject(self) { |all, scope| all.or(where(id: scope)) }
    end

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