[Feature request] ActiveRecord::Relation#negate

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

[Feature request] ActiveRecord::Relation#negate

Maurizio De santis
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)))





--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
To post to this group, send email to [hidden email].
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.