对 Rails 来说还是相当新的。我使用acts_as_votable gem 来创建upvote 和upvote 按钮,以允许用户对笑话进行upvote/downvote,但我不能让他们从upvote/downvote 更改(反之亦然)并在每次点击时更新计数器而不刷新页面。我尝试遵循其他类似的答案,但没有运气。这是我试图实现的。
笑话模型
acts_as_votable
用户模型
acts_as voter
Routes.rb 是
resources :jokes do
member do
get "like" => "jokes#upvote"
get "unlike" => "jokes#downvote"
end
end
笑话控制器是
#upvote from user
def upvote
@joke = Joke.find(params[:id])
@joke.upvote_from current_user
respond_to do |format|
format.html { redirect_to :back }
format.js { render :layout => false }
end
end
#downvote from user
def downvote
@joke = Joke.find(params[:id])
@joke.downvote_from current_user
respond_to do |format|
format.html { redirect_to :back }
format.js { render :layout => false }
end
end
我的观点:
<div class="votes">
<%= link_to like_joke_path(@joke), method: :get, remote: true, class: 'like_joke' do %>
<button type="button" class="btn btn-info" aria-label="Left Align">
<i class="fa fa-arrow-up"></i>
<span class="badge vote_count"><%= @joke.get_upvotes.size %></span>
</button>
<% end %>
<%= link_to unlike_joke_path(@joke), method: :get, remote: true, class: 'unlike_joke' do %>
<button type="button" class="btn btn-info" aria-label="Left Align">
<i class="fa fa-arrow-down"></i>
<span class="badge voute_count"><%= @joke.get_downvotes.size %></span>
</button>
<% end %>
</div>
像.js.erb:
$('.like_joke').bind('ajax:success', function(){
$(this).parent().parent().find('.vote_count').html('<%= escape_javascript @joke.votes_for.size.to_s %>');
$(this).closest('.like_joke').hide();
$(this).closest('.votes').html(' <%= link_to "Unlike", unlike_joke_path(@joke), remote: true, method: :get, class: 'unlike_joke' %>');
});
最后不像.js.erb:
$('.unlike_joke').bind('ajax:success', function(){
$(this).parent().parent().find('.vote_count').html('<%= escape_javascript @joke.votes_for.size.to_s %>');
$(this).closest('.unlike_joke').hide();
$(this).closest('.votes').html(' <%= link_to "Like", like_joke_path(@joke), remote: true, method: :get, class: 'like_joke' %>');
});
这是呈现的 HTML:
<div class="votes">
<a class="like_joke" data-remote="true" data-method="get" href="/jokes/11-cat-joke-title/like">
<button type="button" class="btn btn-info" aria-label="Left Align">
<i class="fa fa-arrow-up"></i>
<span class="badge vote_count">0</span>
</button>
</a>
<a class="unlike_joke" data-remote="true" data-method="get" href="/jokes/11-cat-joke-title/unlike">
<button type="button" class="btn btn-info" aria-label="Left Align">
<i class="fa fa-arrow-down"></i>
<span class="badge voute_count">1</span>
</button>
</a></div>
当我查看 js 控制台时,我在 jquery.js?body=1:9665 处收到内部服务器错误,即 xhr.send( ( options.hasContent && options.data ) || null );
看起来我很接近,但我认为我在我的观点和 js 中搞砸了一些东西。有人可以告诉我我缺少什么吗?