Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

PIVOTAL LABS
Fear of Validation

Interestings

Negate a scope with ActiveRecord

Say you want to negate a scope.

scope :active, -> { where(active: true) }

You start by creating another scope:

scope :inactive, -> { where(active: false) }

Then the underlying column name changes, and you're forced to go back to two different scopes to update it. Ugh.

Wait!

You could have negated the first scope in the second scope!

scope :negate, ->(scope) { where(scope.where_values.reduce(:and).not) }

Now, use it:

scope :inactive, -> { negate(active) }

Boom.

Comments
Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *