我的 ajax 遇到了一个奇怪的错误,其中为视图中的所有帖子激活了“赞”按钮。这个功能的第一次迭代我从来没有遇到过这个问题。它是一个简单的两个状态按钮,如果当前用户不喜欢该帖子,则会隐藏填充的心和空心的心。我的代码写在下面。对于按钮本身,我使用了一个简单的 css 类/png 背景 url。
故事控制器.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
故事\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>
路线.rb
resources :stories do
member do
put 'like', to: 'stories#like'
get 'like', to: 'stories#like'
end
end