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.
Your problem is that this:
doesn't actually change
@instructor.clientsin a way that ActiveRecord will know about.For example:
Same
object_idmeans the same array and no one (but you) will know thatahas actually changed.So
@instructor.clientsis the same object before you addUser.last.idto it as it is after you've pushedUser.last.idonto it and ActiveRecord won't realize that you've changed anything. Then you@instructor.saveand it successfully does nothing at all.You need to create a new array:
The
Array#+creates a whole new array and that will let ActiveRecord know that something has changed. Then your@instructor.savewill 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.