Created
August 18, 2014 20:59
-
-
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.
This file contains 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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Less problems and easier to follow: