Rails, PostgreSQL and... an empty array!

Rails, PostgreSQL and... an empty array!

Hey, this will be my first post in the blog! 👨🏻‍💻

So... Yesterday, I came across an interesting issue or bug... since it's so old and not yet fixed in the latest Rails version.

So, the case is the following:

  1. Rails app with PostgreSQL database
  2. Checking if a value is within an database object's column of type Array
  3. I have a database record of type User with name field equals to Sarah
  4. I have the following array with names: namesArr = ["Helen", "Peter", "Ivan"]

The problem:

I want to find all users with names not within this array get them like this:
User.where('name NOT IN (?)', namesArr)

Everything works fine! But when the nameArr is empty: [] ... The interesting things happen!

The empty array becomes NULL!!! And the SQL query is the following:
SELECT "users".* FROM "users" WHERE (name NOT IN (NULL))

Hmm... Interesting!
And there isn't a fix yet, only workarounds!

My Solution:

It's really silly but it works... I just check if the array is empty and add an empty string:

if nameArr.empty?

Hope that this solution will help you as well! 🙂