Skip to content

Instantly share code, notes, and snippets.

@rondy
Created October 26, 2011 18:55
Show Gist options
  • Save rondy/1317407 to your computer and use it in GitHub Desktop.
Save rondy/1317407 to your computer and use it in GitHub Desktop.
module WhereOr
def where_or(*scopes)
conditions = scopes.inject(self) { |scoped, scope| scoped.send(scope) }
conditions = conditions.where_values.map { |where_value| where_value.respond_to?(:to_sql) ? where_value.to_sql : where_value }
conditions = conditions.join(" OR ")
where(conditions)
end
ActiveRecord::Base.send :extend, self
end
class Person < ActiveRecord::Base
scope :teenager, where("age >= 12 AND age <= 18")
scope :married, where(:married => true)
end
Person.where_or(:teenager, :married) # => "SELECT "people".* FROM "people" WHERE (age >= 12 AND age <= 18 OR "people"."married" = 't')"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment