user9175041
user9175041

Reputation: 29

How to create a JS function on a dynamically generated Rails table

I'm trying to create a JS function to increment the count of the vote on the page, which I would usually do by writing Document.getElementByID and then writing in the ID, but in Rails, I am trying to figure out how to write this function where the table rows are being created dynamically in a loop. How would I create a function to do this?

Here's the html rails loop:

  <tbody>
    <% @requests.each do |request| %>
      <tr>
        <td><%= request.artist %></td>
        <td><%= request.title %></td>
        <td><%= request.voteCount %></td>
        <td><button onclick="upVote()">Vote</button></td>
      </tr>
    <% end %>
  </tbody>

Upvotes: 0

Views: 190

Answers (1)

Jim Ryan
Jim Ryan

Reputation: 698

You've got a few options: If you want to stick with your onclick handler, just pass the request ID to your upVote() function. That might look like this:

<td><button onclick="upVote(<%= request.id %>)">Vote</button></td>

Then, in your JS upVote(requestID) function, do whatever needs to be done to make that request and update your UI accordingly.

Another, superior, option would be to use Rails' built-in remote link_to helper, which is powered by rails-ujs. Here's how that might look:

<td><%= link_to 'Vote', [:upvote, request], remote: true, method: :post, class: 'upvote' %></td>

Note that I'm using the POST method, since actions that have side-effects should not be done with a GET request. Make sure you route accordingly.

Then in your RequestsController:

def upvote
  request = Request.find(params[:id])
  request.upvote! # Or do whatever you need to do to upvote it

  # Respond to your JS request with whatever updated info it might need to update the UI
  render json: { voteCount: request.voteCount } } 
end

Finally, in JS (written as CoffeeScript):

$('a.upvote').on 'ajax:success', (event) ->
  # Update your UI to reflect the upvote (you can access the JSON returned from your upvote action here to make necessary updates)

Upvotes: 1

Related Questions