3

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).

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Chris Wissmach
  • 505
  • 4
  • 11
  • Are you getting the success message? Is `params[:user_name]` getting populated as expected? Separately, you should consider protecting your parameters (see [strong parameters](http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html)). – steve klein Jul 30 '15 at 19:26
  • Yes, I am getting the success message. Even if I manually push to the shared_with field in the rails console, then save it, it doesn't save. – Chris Wissmach Jul 30 '15 at 19:28

1 Answers1

3

.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
Abe Voelker
  • 30,124
  • 14
  • 81
  • 98