我在我的 Rails 应用程序中使用“acts_as_votable”gem,以便用户可以对帖子进行投票。我正在尝试添加 Ajax 功能,以便在用户对帖子进行投票时不必刷新整个页面。
我的 upvote/downvote 链接是可点击的并记录投票,但渲染没有刷新并且投票计数仍然保持不变(我仍然需要刷新页面才能看到计数变化)。
我可以在运行日志中看到这个错误:
Rendered posts/downvote.js.erb (3.4ms)
Completed 500 Internal Server Error in 77ms (ActiveRecord: 8.4ms)
ActionView::Template::Error (undefined method `id' for nil:NilClass):
1: $(document).ready(function(){
2: $('#vote_<%= p.id %>').html("<%= escape_javascript render :partial => 'vote' %>");
3: });
app/views/posts/downvote.js.erb:2:in `_app_views_posts_downvote_js_erb__811382410496335987_70314739481440'
app/controllers/posts_controller.rb:44:in `downvote'
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (1.0ms)
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.7ms)
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb (17.0ms)
这是我所拥有的:
路线.rb
resources :posts do
member do
put "like", to: "posts#upvote"
put "dislike", to: "posts#downvote"
end
end
post_controller.rb
def upvote
@post = Post.find(params[:id])
@post.upvote_by current_user
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
def downvote
@post = Post.find(params[:id])
@post.downvote_by current_user
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
explore.html.erb (/views/pages/explore.html.erb)
<% if @posts.each do |p| %>
<div class="panel-body">
<p class="post-content"><%= auto_link(p.content, :html => { :target => '_blank' }) %></p>
<%= render :partial => '/posts/vote', :class => "vote", :locals => { p: p } %>
</div>
<% end %>
_vote.html.erb (/views/posts/_vote.html.erb)
<<div id="vote_<%= p.id %>" class="vote">
<%= link_to 'Vote Up', like_post_path(p), :class => "upvote", :method => :put, :remote => true %>
<span><%= p.score %></span> <!--show the current vote-->
<%= link_to 'Vote Down', dislike_post_path(p), :class => "downvote", :method => :put, :remote => true %>
</div>
upvote.js.erb (/views/posts/upvote.js.erb)
$(document).ready(function(){
$('#vote_<%= p.id %>').html("<%= escape_javascript render :partial => 'vote' %>");
});
downvote.js.erb (/views/posts/downvote.js.erb)
$(document).ready(function(){
$('#vote_<%= p.id %>').html("<%= escape_javascript render :partial => 'vote' %>");
});
我的 javascript 有问题,还是我渲染有问题?先感谢您。