Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails + Postgres JSON fields and update_column

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?

like image 453
hobberwickey Avatar asked Nov 08 '14 22:11

hobberwickey


1 Answers

Nevermind, I found a solution.

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

Seems obvious in hindsight.

like image 121
hobberwickey Avatar answered Oct 22 '22 03:10

hobberwickey