Skip to content

Instantly share code, notes, and snippets.

@acook
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save acook/9240731 to your computer and use it in GitHub Desktop.

Select an option

Save acook/9240731 to your computer and use it in GitHub Desktop.
module AnyOf # makes "OR" queries
def any_of *queries
queries.inject(arelify queries.pop) do |these, query|
these.or arelify query
end
end
private
def arelify query # tempting to move this into a "to_arel" method
ActiveRecord::Relation === query && query.arel.ast.cores.last.wheres || query
end
end
class User < ActiveRecord::Base
extend AnyOf
scope(:assignable) { where role: 0 }
scope(:unknown) { where role: nil }
scope(:unroled){ where any_of(assignable, unknown) }
# SQL: "SELECT `users`.* FROM `users` WHERE ((`users`.`id` IS NULL OR `users`.`id` = 0))"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment