Clicking on the array as a table column and then saving the model

I have a table with an array as one of the fields (shared_with: string, array: true, default: []). When I push something to this array and save it, it doesn't save what I inserted into it and just go back to what I originally created. Here's a method that should push the new value into the array and store 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 the post method that gets called when the button is clicked. params [: model_id] returns the correct ID of the model that I want, and params [: user_id] returns the correct ID of the user I want to add to the field.

Does anyone know why it won't save the rejected value when saving it? The SQL command in the rails server log doesn't even say it updated that column (my database is postgresql).

+3


source to share


1 answer


.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 can make the model method .changed?

return false, which means there save

will be no-op.



Try the following:

@model.shared_with += [@user.id.to_s]
@model.save

      

+3


source







All Articles