Question

I want to update a model using controller#update. I want to do this via AJAX and without having a hidden form or any DOM elements to keep in sync with my JS data.

How can I submit data to a controller#update via jQuery ajax?

My JS:

$.ajax({
  type: "PATCH",
  url: "/uploads/" + current_upload.id,
  data: { 
    "upload[user]": user.id,
    "upload[upload]": current_upload.id 
  }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

My Controller:

  def update
    @upload = Upload.find(params[:id])

    # update the model.
    if @upload.update(upload_params)
      redirect_to @post
    else
      render 'edit'
    end
  end

  private
    def upload_params
      # permit! allows all attributes.
      params.require(:upload).permit(:user)
    end

Error:

User(#70101060061080) expected, got String(#70101055761460)
Was it helpful?

Solution

Change "upload[user]": user.id to be "upload[user_id]": user.id.

Within Rails, it's trying to assign user (a user instance) to be the string you're passing in via user.id, and complaining about the type mismatch.

OTHER TIPS

It sounds like your request parameters have the "upload" parameter set to be "13" rather than a hash.

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