New data not persisting to Rails array column on Postgres

I have a user model with a friends column of type text. This migration was ran to use the array feature with postgres:

add_column    :users, :friends, :text, array: true

The user model has this method:

def add_friend(target)
  #target would be a value like "1234"
  self.friends = [] if self.friends == nil
  update_attributes friends: self.friends.push(target)
end

The following spec passes until I add user.reload after calling #add_friend:

it "adds a friend to the list of friends" do
  user = create(:user, friends: ["123","456"])
  stranger = create(:user, uid: "789")
  user.add_friend(stranger.uid)
  user.reload #turns the spec red
  user.friends.should include("789")
  user.friends.should include("123")
end

This happens in development as well. The model instance is updated and has the new uid in the array, but once reloaded or reloading the user in a different action, it reverts to what it was before the add_friend method was called.

Using Rails 4.0.0.rc2 and pg 0.15.1

What could this be?


Solution 1:

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.

Solution 2:

It looks like the issue might be your use of push, which modifies the array in place.

I can't find a more primary source atm but this post says:

One important thing to note when interacting with array (or other mutable values) on a model. ActiveRecord does not currently track "destructive", or in place changes. These include array pushing and poping, advance-ing DateTime objects. If you want to use a "destructive" update, you must call <attribute>_will_change! to let ActiveRecord know you changed that value.