视图中数据库值和值显示之间存在奇怪的差异

时间:2011-03-19 23:15:44

标签: ruby-on-rails ruby ruby-on-rails-3

所以我实现了一个投票系统,在我的视图中我打印video.vote_sum,其中一个视频的vote_sum值显示1.但是当我在我的控制台中运行Video.find(450)时,我看到该元素实际上有一个vote_sum为2。我不确定为什么会这样,虽然投票工作正常,但当我重新加载页面时,我视图中的pluralize方法显示“1票”。但这只是在页面重新加载时。当我投票时,它显示“1票”。怪异。

这是video_votes控制器中的create方法:

def create       
  @video = Video.find(params[:video_id])
  @vote = current_user.video_votes.find_or_create_by_video_id(@video.id)

  if @vote.value.nil?
    if params[:type] == "up"
      @vote.value = 1
    else
      @vote.value = -1
    end
  elsif (params[:type] == "up" && @vote.value == 1) || (params[:type] == "down" && @vote.value == -1)
    @vote.value = 0
  elsif ((params[:type] == "up" && @vote.value == -1) || (params[:type] == "down" && @vote.value == 1)) || (@vote.value == 0)
    if params[:type] == "up"
      @vote.value = 1
    else
      @vote.value = -1
    end
  end  

  if @vote.save
    respond_to do |format|
      format.html { redirect_to @video }
      format.js
    end
  else
    respond_to do |format|
      format.html { redirect_to @video }
      format.js {render 'fail_create.js.erb'}
    end
  end  
end

以下是我的视频模型中的相关代码:

def vote_sum
  video_votes.sum(:value)
end

这是我的video_vote模型中的相关代码:

after_update :update_vote_sum

private

  def update_vote_sum
    video.update_attributes!(:vote_sum => video.vote_sum + value)
  end

为什么会发生这种情况,我该如何解决?

2 个答案:

答案 0 :(得分:0)

您应该重新加载视频:

if @vote.save
  @video.reload
  respond_to do |format|
    format.html { redirect_to @video }

可能还有其他方法可以在不重新加载vote_sum的情况下重新加载@video,但这应该足够开始。


另请注意,当您将:counter_cacheup投票分开以分隔关系/模型时,您可以更好地使用模型down ...这很难过但有时会变满你需要用你的模型做出怪异的东西。

答案 1 :(得分:0)

我认为这是您的观点以及您使用pluralize的方式的问题 - 您应该将其传递给您的名词的单数版本,并且可选 a复数版(如果无法正确猜出)。

请参阅my change on GitHub

以下是截图:

Screenshot

[更新]

在弄乱你的应用程序之后,不知何故可以使video.vote_sum(实际数据库值)与video.video_votes.sum(:value)不同;我还不确定为什么。但是,您的代码库存在另一个问题,如下所示:

ruby-1.9.2-p136 :001 > v = Video.find 2
 => #<Video id: 2, ... video_votes_count: 0, vote_sum: 3> 
ruby-1.9.2-p136 :002 > v.video_votes.sum(:value)
 => 2 
ruby-1.9.2-p136 :003 > v.vote_sum
 => 2 # doesn't match vote_sum in the database!

您的vote_sum模型上有一个名为Video的方法。这意味着当您访问@video.vote_sum时,您无法访问vote_sum来自数据库的模型的属性,因为您覆盖了该功能。这使得更新vote_sum的{​​{1}}中的VideoVote毫无意义,因为您永远无法访问它(如上面的IRB会话所示)。

相关问题