jsonpostgresqlrails-4-2-1

How do I query with JSON function/operator where key is either not null or is null?


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.


Solution

  • 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")