jbhannah / invert_where_test

Demonstrating a gotcha with Rails 7's invert_where query method

Home Page:https://jbhannah.net/articles/rails-7-using-invert-where-safely

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Testing #invert_where vs. explicit scope inversion

#invert_where inverts all preceding #where clauses in an ActiveRecord query chain, including those contained within scopes. Instead, retrieving and inverting the [Arel::SelectManager#constraints][constr] of just the desired scope allows for order-independent scope chaining without side effects.

Given the scopes defined in theFoobar model:

Foobar.active.published
# SELECT "foobars".* FROM "foobars" WHERE "foobars"."expires_at" >= '2021-12-10 04:21:48.044576' AND "foobars"."published" = 1

Foobar.published.active
# SELECT "foobars".* FROM "foobars" WHERE "foobars"."published" = 1 AND "foobars"."expires_at" >= '2021-12-10 04:21:48.044576'

Foobar.expired_inverse_of.published
# SELECT "foobars".* FROM "foobars" WHERE NOT ("foobars"."expires_at" >= '2021-12-10 04:21:48.044576') AND "foobars"."published" = 1

Foobar.published.expired_inverse_of
# SELECT "foobars".* FROM "foobars" WHERE "foobars"."published" = 1 AND NOT ("foobars"."expires_at" >= '2021-12-10 04:21:48.044576')

Foobar.expired_invert_where.published
# SELECT "foobars".* FROM "foobars" WHERE "foobars"."expires_at" < '2021-12-10 04:21:48.044576' AND "foobars"."published" = 1

Foobar.published.expired_invert_where
# SELECT "foobars".* FROM "foobars" WHERE NOT ("foobars"."published" = 1 AND "foobars"."expires_at" >= '2021-12-10 04:21:48.044576')

About

Demonstrating a gotcha with Rails 7's invert_where query method

https://jbhannah.net/articles/rails-7-using-invert-where-safely


Languages

Language:Ruby 85.1%Language:HTML 13.0%Language:CSS 1.8%Language:JavaScript 0.2%