1

I am building a Rails 5.2 app. I am using Postgres. In this app I have a User object and in this object i got a JSONB column.

I need to be able to query specific attributes within the JSONB object.

This is how I define it in the User model:

serialize :preferences
store_accessor :preferences, PREFERENCES

This is the content of the object:

{"digest_is_active"=>true, "digest_frequency"=>"modal", "digest_time"=>"10:00"}

I tried this:

scope :digest_active, -> { where("preferences @> ?", { "digest_is_active": true }.to_json) }

User.where("preferences->>'digest_time' = ?", "10:00")

The query seems to run without errors but cannot find the User object.

 SELECT  "users".* FROM "users" WHERE (preferences @> '{"digest_is_active":true}') LIMIT $1  [["LIMIT", 11]]
3
  • What you show as the content of the object is not valid JSON. Commented May 8, 2022 at 15:47
  • What is that final query you show, is that your rails code actually produces, or is that you want it to produce? Commented May 8, 2022 at 15:51
  • @jjanes the query is what my scope outputs when executing Commented May 8, 2022 at 16:24

1 Answer 1

1

Don't do this:

serialize :preferences

That will encode your Ruby hash as a blob of YAML text and then that string will go into your jsonb column. A string is valid JSON so the database will be fine with this but it won't understand the internal structure so the database's JSON operators won't be much use.

Remove the serialize from your model, fix any existing data, and you should have more luck with your queries.

Sign up to request clarification or add additional context in comments.

2 Comments

Sounds interesting, what do you mean by "fix any existing data"? How can I convert?
Pull each column value out, decode the YAML, put it back into the database as proper JSON: stackoverflow.com/a/40555436/479863

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.