instance method
invert_where
Ruby on Rails 7.2.3
Since v7.0.10Signature
invert_where()
Allows you to invert an entire where clause instead of manually applying conditions.
class User scope :active, -> { where(accepted: true, locked: false) } end User.where(accepted: true) # WHERE `accepted` = 1 User.where(accepted: true).invert_where # WHERE `accepted` != 1 User.active # WHERE `accepted` = 1 AND `locked` = 0 User.active.invert_where # WHERE NOT (`accepted` = 1 AND `locked` = 0)
Be careful because this inverts all conditions before invert_where call.
class User scope :active, -> { where(accepted: true, locked: false) } scope :inactive, -> { active.invert_where } # Do not attempt it end # It also inverts `where(role: 'admin')` unexpectedly. User.where(role: 'admin').inactive # WHERE NOT (`role` = 'admin' AND `accepted` = 1 AND `locked` = 0)
Source
# File activerecord/lib/active_record/relation/query_methods.rb, line 1081
def invert_where
spawn.invert_where!
end
Defined in activerecord/lib/active_record/relation/query_methods.rb line 1081
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::QueryMethods