Skip to content

Instantly share code, notes, and snippets.

@ippeiukai
Last active August 29, 2015 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ippeiukai/516b21fe48ea413ef114 to your computer and use it in GitHub Desktop.
Save ippeiukai/516b21fe48ea413ef114 to your computer and use it in GitHub Desktop.
A hack to make `where(relation.exists)` work in 4.2. See https://github.com/rails/rails/issues/16959 for details of the problem and proposed proper solution.
module ActiveRecordRelationExists
# DANGER this switches ActiveRecord::Relation#exists from delegation to arel to our implementation that returns a String with a twist.
# This achieves the most common usage of #exists before 4.2. Proper fix will be: https://github.com/rails/rails/issues/16959
def exists
SqlStringWithNot.new("EXISTS (#{self.to_sql})")
end
class SqlStringWithNot < String
def not
self.class.new("NOT (#{self})")
end
def to_sql
self.to_s
end
end
end
ActiveRecord::Relation.send(:include, ActiveRecordRelationExists)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment