[Feature request] ActiveRecord::Relation#negate


I’ve always felt the needing of a method which negates an ActiveRecord relation. Consider the following use case:

class Content < ApplicationRecord
scope :published, -> { where(status: :publication).where(arel_table[:published_at].lteq ‘NOW()’ }
scope :not_published, -> { where.not(status: :publication).or(where(arel_table[:published_at].gt ‘NOW()’) }

with an ActiveRecord::Relation#negate method, the unpublished scope would just be something like

scope :not_published, -> { where published.negate }

I’m somehow already using a negation based on an ActiveRecord::Relation instance, which is

scope :not_published, -> { where public.where_clause.invert.ast }

But can be used only when there are no values for prepared statements, otherwise it raises the following error:

ActiveRecord::StatementInvalid: PG::ProtocolViolation: ERROR: bind message supplies 0 parameters, but prepared statement “” requires 1
: SELECT “contents”.* FROM “contents” WHERE (NOT ((“contents”.“status” != $1)))