Rails acts_as_votable ajax button is liking all posts

102 Views Asked by At

I'm facing a weird bug with my ajax, where the like button is activating for all post in the view. I never had this issue with the first iteration of this feature. Its a simple two state like button that hides the filled heart with the empty heart if the current user isn't liking the post. The code that I have is written below. For the buttons themselves, I'm using a simple css class/png background url.

stories_controller.rb

def like
    @story = Story.friendly.find(params[:id])
    if !current_user.liked? @story
      @story.liked_by current_user
    elsif current_user.liked? @story
      @story.unliked_by current_user
    end

    respond_to do |format|
      format.js {render :nothing => true }
    end
  end

stories\like.js.erb

<% if current_user.liked? @story %>
$('#like-story-id').removeClass('story-heart-btn').addClass('story-heart-btn-active');
<% else %>
$('#like-story-id').addClass('story-heart-btn-inactive');
<% end %>
$('.likes-story-count').html("<%= @story.get_upvotes.size %>");

_story.html.erb

<ul id="left-story-footer-list">
        <li class="story-votes" id="#story_<%= story.id %>">
          <%= link_to like_story_path(story), style: 'text-decoration: none', class: 'like-story-btn', method: :put, remote: true do %>
            <div class="story-heart-btn" id="like-story-id"></div>
          <% end %>
        </li>
        <li><p class="story-card-text-format likes-story-count"><%= number_with_delimiter(story.get_likes.size) %></p></li>

      </ul>

routes.rb

resources :stories do
    member do
      put 'like', to: 'stories#like'
      get 'like', to: 'stories#like'
    end
  end
1

There are 1 best solutions below

3
Nezir On

Doesn't this like-story-id should also be a unique inside ul?

<div class="story-heart-btn" id="like-story-id"></div>