Skip to content

Instantly share code, notes, and snippets.

@pocke
Created April 28, 2021 10:54
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 pocke/6c39b2eb215cdc117b996c987dc605ab to your computer and use it in GitHub Desktop.
Save pocke/6c39b2eb215cdc117b996c987dc605ab to your computer and use it in GitHub Desktop.
`invert_where` inverts all where clause (dangerous!)
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Activate the gem you are reporting the issue against.
gem "activerecord", github: 'rails/rails'
gem "activemodel", github: 'rails/rails'
gem "activesupport", github: 'rails/rails'
gem "sqlite3"
end
require "active_record"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.string :a
t.string :b
end
end
class Post < ActiveRecord::Base
has_many :comments
end
puts
puts
puts Post.where(a: 'a').where(b: 'b').to_sql
puts Post.where(a: 'a').where(b: 'b').invert_where.to_sql
$ ruby invert_where.rb
Fetching https://github.com/rails/rails.git
Fetching gem metadata from https://rubygems.org/......
Fetching gem metadata from https://rubygems.org/............
Fetching gem metadata from https://rubygems.org/............
Resolving dependencies...
Using bundler 2.2.15
Using concurrent-ruby 1.1.8
Using sqlite3 1.4.2
Using minitest 5.14.4
Using i18n 1.8.10
Using zeitwerk 2.4.2
Using tzinfo 2.0.4
Using activesupport 7.0.0.alpha from https://github.com/rails/rails.git (at main@adc0146)
Using activemodel 7.0.0.alpha from https://github.com/rails/rails.git (at main@adc0146)
Using activerecord 7.0.0.alpha from https://github.com/rails/rails.git (at main@adc0146)
-- create_table(:posts, {:force=>true})
   -> 0.0032s


SELECT "posts".* FROM "posts" WHERE "posts"."a" = 'a' AND "posts"."b" = 'b'
SELECT "posts".* FROM "posts" WHERE NOT ("posts"."a" = 'a' AND "posts"."b" = 'b')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment