[Feature request] ActiveRecord::Relation#negate

18 views
Skip to first unread message

Maurizio De Santis

unread,
Mar 24, 2017, 3:56:14 PM3/24/17
to Ruby on Rails: Core
Hello,

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()') }
  end

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)))





Reply all
Reply to author
Forward
0 new messages