Search code examples
ruby-on-railsruby-on-rails-4put

Rails updates with contenteditable


My controller builds an index that nicely tabulates a whole lot of its content. I have made each td contenteditable. Onblur, I would like to submit updated data.

In order to find the correct row, I have given each tr the model's id (as a name) but I only want to update the one attribute, not the whole model. My js looks something like this:

$.ajax({
    type: 'PUT',
    url:  '/songs/'+$(this).parent("tr").attr("name"),
    data: {$(this).attr("name"): $(this).html()},
    dataType: "JSON",
    success: function(data) {
        console.log(data);
    }
});

but of course, this doesn't work (because of the "data:" line). The key though, is what data I actually need to submit for my controller's update_attributes to work. How to serialize it is not my first concern.


Solution

  • Rails will combine the parameters in the URL (the id) and the data that gets sent by post. So my js is now (this happens on blur):

    $.ajax({
        type: 'PUT',
        url:  '/songs/'+$(this).parent("tr").attr("name"),
        data: dataToSend,
        dataType: "JSON",
        success: function(data) {
            console.log(data);
        }
    });
    

    But on the server side the key is update_attribute where the highlights are:

    def update
        @song = Song.find(params[:id])
        @song.update_attributes params[:key] => params[:value]
    end