Rails還是比較新的。我使用acts_as_votable gem來創建upvote和upvote按鈕,以允許用戶upvote/downvote笑話,但我不能讓他們從upvote/downvote(反之亦然)更改,並在每次點擊時更新計數器而不刷新頁面。我嘗試了其他類似的答案,但沒有運氣。這是我試圖實現的。Rails upvote/downvote使用Ajax和acts_as_votable
笑話模型
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>
like.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' %>');
});
終於unlike.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)||空值 );
看起來我很接近,但我認爲我在我的觀點和js中搞砸了一些東西。有人能告訴我我錯過了什麼嗎?
謝謝!我已經添加了呈現的HTML以及我從js控制檯獲得的錯誤,以及它被絆倒的代碼行。 –
@GregSéguin確定,更新了我認爲可能會發生的事情。有一個去與看看。 –