Today I Learned

hashrocket A Hashrocket project

ActiveRecord.invert_where

Ever been debugging in ActiveRecord and wanted to inverse a query? You can do that without changing the whole query!

User.where(active: true)
# => "select * from users where active = 'true'"

User.where(active: true).invert_where
# => "select * from users where active != 'true'"

It also works with multiple conditions:

User.where(active: true, subscribed: false)
# => "select * from users where active = 'true' and subscribed = 'false'"

User.where(active: true, subscribed: false).invert_where
# => "select * from users where active != 'true' and subscribed != 'false'"

It works on scopes, too:

class User < ActiveRecord::Base
  scope :active, -> { where(active: true) }
end

User.active.invert_where
# => "select * from users where active != 'true'"
See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.