Skip to content

Instantly share code, notes, and snippets.

@tlowrimore
Created March 27, 2013 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlowrimore/5257360 to your computer and use it in GitHub Desktop.
Save tlowrimore/5257360 to your computer and use it in GitHub Desktop.
OR's together provided scopes, returning an ActiveRecord::Relation. This implementation is smart enough to not only handle your _where_ clauses, but it also takes care of your joins! *Note* This is a work in progress, so it has room to grow
module ActiveRecord::OrScope
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def or_scope(*scopes)
conditions =
scopes
.map { |scope| "(#{scope.where_clauses.map{ |clause| "(#{clause})"}.join(" AND ")})" }
.join(" OR ")
relationships =
scopes
.map { |scope| scope.joins_values }
.flatten
.uniq
joins(*relationships).where(conditions)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment