Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update a data record's value with Ruby on Rails 4.0.1/PostgreSQL Hstore?

I'm encountering a strange issue that must be user error on my part but can't figure it out.

I'm using Ruby 1.9.3-p194, Rails 4.01, PostgreSQL.

I have a model, Customer, with a column called data that is a hstore type. For some reason, I am not able to update the data (hstore) column with any new key/values nor can I update an existing key's value. I can do an insert and specify any key/values w/o any issue.

Customer id: 1, first_name: "Mark", last_name: "Test", data: {"balance"=>"0"}, created_at: "2013-11-27 14:39:09", updated_at: "2013-11-27 14:39:09"

c.data["balance"] = "100"

c.save

(0.2ms) BEGIN

(0.3ms) COMMIT => true

If I do an update_attributes, it does save it.

c.update_attributes({:data => {"balance" => "343"}})

I don't see any errors or exceptions when I used c.save!. Anyone have any ideas?

like image 923
james Avatar asked Nov 27 '13 19:11

james


2 Answers

I still needed this to work now and couldn't wait for the bug to be solved, so here's my workaround:

c.data["balance"] = "100"
c.data_will_change!
c.save

... and it will save to the DB!

The "attribute_name_will_change!" method isn't that well documented and can be found in the introduction to the Active Model Dirty module: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html

like image 92
wdspkr Avatar answered Sep 22 '22 05:09

wdspkr


Ok finally found an answer to my question. Turns out that it's a bug within Rails 4.0.

"ActiveRecord Hstore bug: can't update a key in the hash" https://github.com/rails/rails/issues/6127

like image 27
james Avatar answered Sep 20 '22 05:09

james