4

I am just starting to use the array data-type in Postgres with Rails 4 but I am having trouble getting values on an existing array to update. I have a column called 'quantity' that is an array of integers( [0,0] ). I want to update the value at 'quantity[0]' and I have tried the following in the console:

a = Asset.find(2) 
=> #<Asset id: 2, quantity: [0,0]>

a.quantity[0] = 5
=> 5 

a.quantity_will_change! 
=> [5, 0] 

a.save
=> true

a.reload
=> #<Asset id: 2, quantity: [0,0]>

As you can see, the asset object's quantity value is change but when I try to save the object using 'a.save' the change is not reflected when I reload the object.

Any help would be greatly appreciated.

Thanks

mu is too short
  • 426,620
  • 70
  • 833
  • 800
louism2
  • 350
  • 4
  • 18
  • 1
    `quantity_will_change!` or replacing the whole array should work. Is there something going on that we can't see? – mu is too short Nov 14 '13 at 23:23
  • 1
    @muistooshort : you were 100% correct. I had a callback on my model that was altering the values. I appreciate the help. – louism2 Nov 19 '13 at 16:49

2 Answers2

2

My reading of http://apidock.com/rails/ActiveRecord/Dirty is that you have to call ..._will_change! before you change the attribute. You should be able to confirm this by examining changes under various scenarios.

Update: I just tested the behavior with a string attribute, and it still saves the updated string even if the change was made before ..._will_change is called, so my interpretation may be off.

Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106
  • Hey Peter, I have tried using _quantity_will_change!_ both before and after setting the value. The _changes_ method does in fact show that the value was changed. Any other ideas? Thanks for your help. – louism2 Nov 14 '13 at 23:19
  • 1
    Only thing I can think of is what @muistooshort indicated, that something else is going on (e.g. within your model that is "resetting" things). – Peter Alfvin Nov 14 '13 at 23:25
1

<attribute>_will_change! will only update value if array has been replaced. In-place modifications like []= won't be saved at all.

dredozubov
  • 715
  • 1
  • 6
  • 11