我的ajax遇到了一个怪异的错误,其中对视图中的所有帖子都激活了like按钮。在此功能的第一次迭代中,我从未遇到过这个问题。它是一个简单的类似两种状态的按钮,如果当前用户不喜欢该帖子,则该按钮将用空的心隐藏填充的心。我的代码写在下面。对于按钮本身,我使用的是简单的CSS类/ png背景网址。
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
答案 0 :(得分:0)
这个like-story-id在ul内部也不应该是唯一的吗?
<div class="story-heart-btn" id="like-story-id"></div>