Skip to content

Instantly share code, notes, and snippets.

@3014zhangshuo
Forked from annikoff/arel_any_predicate.rb
Created September 20, 2019 12:26
Show Gist options
  • Save 3014zhangshuo/eb8760dee9e06ae063e1994a4102faa6 to your computer and use it in GitHub Desktop.
Save 3014zhangshuo/eb8760dee9e06ae063e1994a4102faa6 to your computer and use it in GitHub Desktop.
An example of how to add a custom predicate to Arel
module Arel::Predications
def any(right)
Arel::Nodes::Any.new(self, quoted_node(right))
end
end
class Arel::Nodes::Any < Arel::Nodes::Binary
def operator
:'ANY'
end
end
class Arel::Visitors::PostgreSQL
private
def visit_Arel_Nodes_Any(o, collector)
collector = visit o.right, collector
collector << " = #{Arel::Nodes::Any.new(nil, nil).operator} ("
visit(o.left, collector) << ")"
end
end
puts User.where(User.arel_table[:roles].any('superadmin')).to_sql
SELECT "users".* FROM "users" WHERE ('superadmin' = ANY ("users"."roles"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment