Mind Dump, Tech And Life Blog
written by Ivan Alenko
published under license Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)copy! share!
posted at 11. Aug '21

Ruby on Rails 5.2 vs. 6.0 where.not Semantics

There is a big difference between chained where.not operators of ActiveRecord in Ruby on Rails 5.2 and 6.0. The generated SQL code is different.

Let’s say we have multiple scopes with multiple WHEREs:

Article
  .where(cond1)
  .where(cond2)
  .where.not(cond3)
  .where.not(cond4)
).or(
  Article
    .where(cond1)
    .where(cond5)
    .where.not(cond3)
    .where.not(cond4)
  )

Ruby on Rails 5.2 chained where.not are kind of incorrect:

WHERE cond1
  AND NOT cond3
  AND NOT cond4 # transformation AND NOT (cond3 OR cond4)
  AND (cond2 OR cond5)

Ruby on Rails 6 chained where.not are correct:

WHERE cond1
  AND NOT (cond3 AND cond4) # transformation: AND (NOT cond3 OR NOT cond4)
  AND (cond2 OR cond5)

Rail 6 version is kind of more correct.

Add Comment