coderk
coderk

Reputation: 71

acts_as_votable javascript html table

I'm trying to use the acts_as_votable gem in ruby on rails. However, I get stuck when I need to add the button to the view.

I want to add a voting system to a list of item which are put into an html table as users fill out the form in the web browser.

I can insert a 'like' button in each row for each 'destination' item. However, does this mean I need to write a 'attachLikeHandler' function to deal with what happens when the like button is clicked?

Here is the dashboard.js:

var insertDest = function(dest) {
  // Find a <table> element with id="myTable":
  var table = document.getElementById("destTable");

  // Create an empty <tr> element and add it to the 1st position of the table:
  var row = table.insertRow(1);

  // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:

  var name_cell = row.insertCell(0);
  var address_cell = row.insertCell(1);
  // var delete_cell = row.insertCell(2);

  var like_cell = row.insertCell(2);
  like_cell.innerHTML = '<input class="Like" type="button" value="Like" />';
  var like_count_cell = row.insertCell(3);
  like_count_cell.innerHTML= 0;

  // Add some text to the new cells:
  name_cell.innerHTML = dest.name;
  address_cell.innerHTML = dest.address;
  // delete_cell.innerHTML = "<div class='del'>x</div>";
  addMarker(dest.address,map);
};

var insertAllDest = function(trip){
    var d = trip.destinations;
    for (i in d){
        insertDest(d[i]);
    }
};

Upvotes: 0

Views: 47

Answers (1)

7stud
7stud

Reputation: 48639

However, does this mean I need to write a 'attachLikeHandler' function to deal with what happens when the like button is clicked?

Yes:

$(".like").on('click', function() {
  $.ajax({
      method: "PUT",
      url: "/photos/" + $(this).attr("id"),   
      success: function(msg_from_server) {
        alert(msg_from_server);  //"Thanks for voting!" or "Sorry, you already voted!"
      }
  });
});

If you have a route declared as resources :photos, then a url like /photos/12 will send a request to photos#update, then inside the update action params[:id] will be 12. Note that you'll need to add the resource id to the html when constructing the html.

Upvotes: 1

Related Questions