New data not persisting to Rails array column on Postgres

I suspect that ActiveRecord isn’t noticing that your friends array has changed because, well, the underlying array reference doesn’t change when you:

self.friends.push(target)

That will alter the contents of the array but the array itself will still be the same array. I know that this problem crops up with the postgres_ext gem in Rails3 and given this issue:

String attribute isn’t marked as dirty, when it changes with <<

I’d expect Rails4 to behave the same way.

The solution would be to create a new array rather than trying to modify the array in-place:

update_attributes friends: self.friends + [ target ]

There are lots of ways to create a new array while adding an element to an existing array, use whichever one you like.

Leave a Comment