Adding a record in Rails through javascript

Problem

You would like to trigger a record insertion after a specific action has happened through javascript (ie drag – drop an item into a container), in a rails application.

 

Solution

You would need to get the object attributes from the html page somehow (ie user_id and user_name), and then have a function in your application js that calls the post function.

So if you have a drag and drop container for example then the code in the application.js should be like the following:

$("#name_of_container").droppable({
  drop: handleDropEvent
});

function handleDropEvent(event,ui) {
  var user_id = ui.draggable.attr("user_id");
  var user_name = ui.draggable.attr("user_name");
  $.post('/users', {user: {user_id: user_id, name: user_name}})
}