Pieterjan
Pieterjan

Reputation: 475

Rails JSON store value gets quoted upon saving

I have this problem with my Rails (5.1.6) application that is running on a PostgreSQL instance.

I have a model with a JSON type column (t.json :meta). The model has a store accessor like

store :meta, accessors: [:title], coder: JSON

The problem is now when I set this value that it shows up in the database as

"{\"title\":\"I am a title\"}"

making it text rather than a JSON value, which in turn makes that I cannot use the JSON query operator (->>) to query my JSON fields. I already tried without the coder option, but this results in it being saved as YAML. The serialize function also did not change anything for me (adding serialize :meta, JSON)

Any and all help is appreciated!

Upvotes: 1

Views: 1100

Answers (1)

max
max

Reputation: 102443

serialize and store are not intended to be used for native JSON columns. Their purpose is to marshal and un-marshal data into string columns.

This was a "poor mans" JSON storage before native JSON support existed (and was supported by ActiceRecord). Using it on a JSON column will result in a double encoded string as you have noticed.

You don't actually have to do anything to use a JSON column. Its handled by the adapter.

See:

Upvotes: 3

Related Questions