6

I've been playing around Rails (4) + Postgres JSON fields a bit now, and I've noticed that if I do something like this

model.json_data = {
   field1: "hello",
   field2: "world"
}
model.save

it works fine. However if I do

model.update_column(:json_data, {
   field1: "hello",
   field2: "world"
} )

it doesn't work. It doesn't seem like update_column is storing the data as JSON, but just a string with line breaks and tabs included. The problem is, I want the json_data to be generated in an after_save callback, so I need to not re-trigger the after_save callback when updating the JSON field.

Any thoughts on what might be going on here, or how to get around it?

1 Answer 1

12

Nevermind, I found a solution.

model.update_column(:json_data, {
   field1: "hello",
   field2: "world"
}.to_json )

Seems obvious in hindsight.

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

1 Comment

A bit of waning (Rails 5.2) - this seems to store the value (or retrieve it) as a String. To bypass callbacks I implemented the conditional callback

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.