I have a table with an array as one of it's fields (shared_with:string, array:true, default: []). When I push something to this array and save it, it doesn't save what I pushed into it, and just goes back to what I initially created it as. Here's the method that should be pushing the new value into the array and saving it:
def new_share
@model = Model.find(params[:model_id])
if User.find_by_name(params[:user_name]) != nil
@user = User.find_by_name(params[:user_name])
@model.shared_with.push(@user.id.to_s)
if @model.save
render :json => {:success => true, :message => "User successfully added"}
else
end
else
render :json => {:success => false, :message => "Cannot find user"}
end
end
This is a post method that is called when I click a button. params[:model_id] returns the correct id of the Model that I want, and params[:user_id] is returning the correct id of the User that I want to add to the field.
Does anyone know why it would not save the pushed value when it's saved? The SQL command in the rails server log doesn't even say that it has updated that column (my database is postgresql).
.push mutates the array in-place, which won't update its object ID:
a = [1,2,3]
a.object_id # => 12011120
a.push(4)
a.object_id # => 12011120
Just a theory, but this may make the model's .changed? method return false, which means save will be a no-op.
Try this:
@model.shared_with += [@user.id.to_s]
@model.save
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With