6

I am looking for the active record version of the following sql code:

select *
from users
where (details->'email') is not null

Let's say that my User model has a json field called, details, and some records will have an email key-value and some will not. I'm trying to query the user records that have an email, key-value. I tried using the following, User.where("details->'email' is not null"), but my terminal prints out this:

PG::UndefinedFunction: ERROR:  operator does not exist: json -> boolean

I found this SO post, which attempts to do the opposite query, but the idea is the same. If someone can show me the Active Record version of querying where a json key is or is not present, I'd greatly appreciate it.

Community
  • 1
  • 1
robskrob
  • 2,720
  • 4
  • 31
  • 58

1 Answers1

10

This worked for getting users with an email key:

User.where("(details->'email') is not null")

This worked for getting users without an email key:

User.where("(details->'email') is null")
robskrob
  • 2,720
  • 4
  • 31
  • 58