Alexkr
Alexkr

Reputation: 3

Ruby on Rails -- Can't get jQuery to update button on click

I have a voting mechanism where you can vote up/down on an entry within a given contest. There are a limited number of votes and every entry has an up and a down button next to it. I would like the up button to change styles if there are no votes remaining and the down button to change styles when the user hasn't voted yet.

In my _entry.html I have:

       <div class="vote-box">
        <% if !current_user.voted?(entry) %>
          <%= link_to '-', entry_vote_down_path(entry), method: :post, remote: true, :class => "btn btn-success vote down disabled" %>
        <% else %>
          <%= link_to '-', entry_vote_down_path(entry), method: :post, remote: true, :class => "btn btn-success vote down" %>
        <% end %>


        <% if current_user.votes_remaining(entry.contest) == 0 %>
          <%= link_to '+', entry_vote_up_path(entry), method: :post, remote: true, :class => "btn btn-success vote up disabled" %>
        <% else %>
          <%= link_to '+', entry_vote_up_path(entry), method: :post, remote: true, :class => "btn btn-success vote up" %>
        <% end %>

          <p><%= pluralize entry.votes.count, 'total vote' %> </p>

The entry_vote_up_path, for example, ultimately triggers vote_up in the EntriesController:

def vote_up
  entry = Entry.find(params[:entry_id])
  current_user.vote_up!(entry)
  flash[:notice] = "Vote successfully counted."

  respond_to do |f|
   f.js { @entry = entry }
  end
end

I then have a vote_up.coffee:

  <% if current_user.votes_remaining(@entry.contest) == 0 %>

  $('#entry_<%= @entry.id %> .vote-box a.vote_up').replaceWith('<%=   vote_up_button_for_entry_disabled(@entry) %>')

  <% else %>

  $('#entry_<%= @entry.id %> .vote-box a.vote_up').replaceWith('<%= vote_up_button_for_entry(@entry) %>')

The vote_up_button_for_entry does the same as the link_to in the original html file, I know this works. I feel like the problem is with the "a.vote_up", but I just can't figure it out. Thanks!

Upvotes: 0

Views: 119

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124419

Your coffeescript file is looking for a vote_up class, but you don't actually use that class anywhere. Instead, you use two separate classes, vote and up.

Either change the link_to entries to actually use vote_up and vote_down, or do something like this:

$('#entry_<%= @entry.id %> .vote-box a.vote.up').replaceWith('<%=   vote_up_button_for_entry_disabled(@entry) %>')

Upvotes: 1

Related Questions