【发布时间】:2018-11-18 22:40:16
【问题描述】:
我有一个带有点赞/不点赞功能的评论模型,当我第一次点赞任何评论时,它可以正常工作,因为点赞链接是使用初始 html.erb 渲染呈现的。但是,当我尝试不喜欢或重新喜欢任何内容时,它总是会分别使用指向我喜欢或不喜欢的第一条评论的链接来更新部分内容。
cmets_controller.rb
def like
@comment = Comment.find(params[:id])
@comment.liked_by current_user
respond_to do |format|
format.html { redirect_to :back }
format.js { render '/comments/like.js.erb' }# layout: false }
end
end
def unlike
@comment = Comment.find(params[:id])
@comment.unliked_by current_user
respond_to do |format|
format.html { redirect_to :back }
format.js { render '/comments/unlike.js.erb' }# layout: false }
end
end
不像.js.erb
$('.unlike_comment').bind('ajax:success', function(){
$(this).parent().parent().find('.vote_count').html('<%= escape_javascript @comment.votes_for.size.to_s %>');
$(this).closest('.unlike_comment').hide();
$(this).closest('.votes').html(' <%= link_to "", like_comment_path(@comment), remote: true, method: :get, class: 'like_comment glyphicon glyphicon-chevron-up', :style=>'color: #cecece;' %>');
});
like.js.erb
$('.like_comment').bind('ajax:success', function(){
$(this).parent().parent().find('.vote_count').html('<%= escape_javascript @comment.votes_for.size.to_s %>');
$(this).closest('.like_comment').hide();
$(this).closest('.votes').html(' <%= link_to "", unlike_comment_path(@comment), remote: true, method: :get, class: 'unlike_comment glyphicon glyphicon-chevron-up', :style=>'color: #202020;' %>');
});
以及 _comment.html.erb 的相关部分
<comment-body>
<p>
<span class="votes">
<% if logged_in? && (current_user.liked? comment) %>
<%= link_to "", unlike_comment_path(comment), method: :get, remote: true, class: 'unlike_comment glyphicon glyphicon-chevron-up', :style=>'color: #202020;' %>
<% elsif logged_in? %>
<%= link_to "", like_comment_path(comment), method: :get, remote: true, class: 'like_comment glyphicon glyphicon-chevron-up', :style=>'color: #cecece;' %>
<% else %>
<%= link_to "", prompt_login_comment_path(comment), method: :get, remote: true, class: 'prompt_login glyphicon glyphicon-chevron-up', :style=>'color: #cecece;' %>
<% end %>
</span>
<%= link_to comment.title, comment, class: 'bigger comment-text' %> <%= link_to comment.body, comment, class: 'notbig comment-text' %>
</p>
</comment-body>
因此,例如,如果我不喜欢评论 4,然后喜欢评论 3,它会将评论 3 中的不同链接部分更改为 cmets/4/unlike。可能出现什么问题会导致这种情况发生?非常感谢任何帮助。
【问题讨论】:
标签: jquery ruby-on-rails ruby ruby-on-rails-5