我有一个张贴、评论和投票模型
每次创建Vote
模型的实例(使用:polarity
+1或-1)时,它都会更新所属帖子的total_votes
列:
投票.rb:
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
before_create :update_total
protected
def update_total
total_average = self.votable.total_votes
self.votable.update_attribute(:total_votes, total_average + self.polarity)
end
end
这就是我在show.html.erb视图中对它的称呼:
<div class="post-<%= @post.id %>">
<h3><span class="vote-count"><%= @post.total_votes %></span> votes</h3><br />
votes_controller.rb的示例:
def vote_up
@post = Post.find(params[:id])
if @post.votes.exists?(:user_id => current_user.id)
@notice = 'You already voted'
else
@vote = @post.votes.create(:user_id => current_user.id, :polarity => 1)
end
respond_to do |format|
format.js
end
end
路由.rb:
get 'votes/:id/vote_up' => 'votes#vote_up', as: 'vote_up'
出于某种原因,如果通过Ajax从以下文件附加到show.html.erb,@post.total_notes会给出0,即列的默认值(无论其实际值是-1还是1):
vote_up.js.erb:
<% unless @notice.blank? %>
alert("<%= @notice %>");
<% end %>
<% unless @vote.blank? %>
$('.post-<%=@post.id%> span.vote-count').html('<%= @post.total_votes %>');
$('.post-<%=@post.id%> div.voted-user').html('<% @post.votes.each do |vote| %><%= link_to vote.user.username, vote.user %><% end %>');
<% end %>
有什么建议可以解决这个问题吗?
您正在加载@post
对象,然后在Vote
模型的回调中对其进行更改,但@post
对象不知道此更改,并继续使用数据库中的缓存结果。您可以通过在@post.votes.create
行后面放一个@post.reload
来强制重新加载它。