Question

If I create an instance variable of a user within the Users controller, then try to add to a field array, I can see it has been added, but when I go to save, it does not save

@instructor = User.find(current_user.id)
@instructor.clients = @instructor.clients << User.last.id
@instructor.save

When I then go to Pry and do the same exact operation with an instance variable I create in Pry, it does save. Why is that and how can I get this to work in the controller?

The array field is a postgres numeric array.

Was it helpful?

Solution

Your problem is that this:

@instructor.clients = @instructor.clients << User.last.id

doesn't actually change @instructor.clients in a way that ActiveRecord will know about.

For example:

>> a = [ ]
>> b = a << 6
>> b.object_id
=> 2165471260
>> a.object_id
=> 2165471260

Same object_id means the same array and no one (but you) will know that a has actually changed.

So @instructor.clients is the same object before you add User.last.id to it as it is after you've pushed User.last.id onto it and ActiveRecord won't realize that you've changed anything. Then you @instructor.save and it successfully does nothing at all.

You need to create a new array:

@instructor.clients = @instructor.clients + [ User.last.id ]

The Array#+ creates a whole new array and that will let ActiveRecord know that something has changed. Then your @instructor.save will actually write the new array to the database and the updated array will be there the next time you pull that instructor out of the database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top