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.
Note: A JSON value of null is a value as far as SQL is concerned. It is not NULL, which in SQL represents the absence of a value (missing, unknown, or inapplicable data). In particular, SQL condition IS NULL returns false for a JSON null value, and SQL condition IS NOT NULL returns true.
Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.
jsonb_build_object(VARIADIC "any") Builds a JSON object out of a variadic argument list. By convention, the argument list consists of alternating keys and values. json_build_object('foo',1,'bar',2)
Expands a JSON array to a set of text values. Returns the type of the outermost JSON value as a text string. Possible types are object, array, string, number, boolean, and null.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With