6

There is a JSONB information field with this structure:

{
  "ignore"=>false
}

I want to get all records whose ignore field is true:

@user.posts.where("information ->> 'ignore' = TRUE")

This line throws an error:

PG::UndefinedFunction: ERROR:  operator does not exist: text = boolean

And I could not find anything in Google. Everywhere we are talking about textual meanings. But there is nothing about booleans.

2 Answers 2

8

You must cast the result of information->>'ignore' to boolean:

@user.posts.where("(information ->> 'ignore')::boolean = TRUE")
Sign up to request clarification or add additional context in comments.

5 Comments

I tried both options - it doesn't work. The result is not filtered - both true and false are present.
Can you add the logs to your question? And also the structure of the posts table (\d+ posts in psql).
Your third option is doing something terrible. I get several times more data than there is in the database. Well, it does not filter anything.
I don't have idea how your tabe looks like, nor about the records there. I asked you for a simple describe of your table, without that is difficult to know what's your problem.
There is a jsonb information field in the table that contains what I showed in the text of the question. A simple table with simple fields.
0

I had the same issue in upgrading to Rails 5/6. It seems the way the pg gem casts has changed a little, but this works for me:

@user.posts.where("(information ->> 'ignore')::boolean = ?", true)

When an argument is added as the second parameter to a where method call, ActiveRecord will do the work to cast this appropriately for you. If you add .explain to the query above, you should see something like:

EXPLAIN for: SELECT ... AND ((information ->> 'ignore')::boolean = TRUE) ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.