Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Postgres hstore. DB not being updated with changed values

I'm trying to understand how to use hstore and it seems the database isn't updated if I try to modify a value in my hash.

In my rails console I do

u = User.new
u.hash_column = {'key' => 'first'}
u.save

I get a message in my console (0.4ms) BEGIN SQL (2.0ms) UPDATE "users" SET "hash_column" = $1, "updated_at" = $2 WHERE ... (18.0ms) COMMIT and when I check in the DB the column has the correct data

now when I try

u.hash_column['key'] = 'second'

the model seems correct in the console

puts u.hash_column

gives {"key"=>"second"}

however when I try to save this u.save in my console I just get (0.3ms) BEGIN (0.2ms) COMMIT with no update statement and when I check the DB the data hasn't changed.

if I change another attribute on the user model and save it hash_column still doesn't get updated. The only way I can change the hash_column in the database seems to be to assign to the complete hash like

u.hash_column = {'key' => 'second'}

is this how it is meant to work or am I doing something wrong?

like image 300
RoyTheBoy Avatar asked Feb 05 '14 12:02

RoyTheBoy


1 Answers

This is due to the way that rails currently tracks changes. It will only track changes when you use the attributes setter (u.hash_column). If you update a value in the hash, you have to notify Rails that the value changed by calling u.hash_column_will_change!. This marks the value as dirty and the next time save is called, it will be persisted.

This also effects arrays and strings and dates. If you call u.string_value.gsub! or u.array_column << value those changes will not be persisted without calling the <column>_will_change! method for those columns

like image 129
Dan McClain Avatar answered Oct 18 '22 18:10

Dan McClain