Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect changes in PostgreSQL json field

I'm using a json field for storing some additional parameters in one of my models.

It works great except for the fact that it doesn't detect changes I make when accessing the data using square brackets:

2.1.1 :002 > p = Payments.last
 => {...}
2.1.1 :003 > p.params.keys
 => ["receipt_data"] 
2.1.1 :004 > p.params['verification_data'] = 'test'
 => "test" 
2.1.1 :005 > p.params.keys
 => ["receipt_data", "verification_data"] 
2.1.1 :006 > p.params_changed?
 => false 
2.1.1 :007 > p.save
   (0.2ms)  BEGIN
   (0.2ms)  COMMIT
 => true 
2.1.1 :008 > Payment.last.params.keys
  Payment Load (0.5ms)  SELECT  "payments".* FROM "payments"   ORDER BY "payments"."id" DESC LIMIT 1
 => ["receipt_data"] 

How do I force it to save the changes?

like image 980
makhan Avatar asked May 05 '14 04:05

makhan


1 Answers

to force, before any update. you can say:

p = Payments.last
p.params_will_change!
p.params['verification_data'] = 'test'
p.save

Btw, ActiveRecord is supposed to handle dirty tracking automatically. so, if you can push an app on github which reproduces this issue, I can try to help.

like image 71
CuriousMind Avatar answered Sep 22 '22 06:09

CuriousMind