2011-03-19 27 views
0

所以我實現了一個投票系統,並在我的視圖中打印video.vote_sum,其中一個視頻的vote_sum的值顯示爲1.但是,當我在我的控制檯中運行Video.find(450) ,我看到這個元素實際上有兩個vote_sum。我不確定爲什麼會發生這種情況,雖然投票的效果應該如此,但當我重新加載頁面時,我的視圖中的pluralize方法顯示「1票」。但這只是在頁面重新加載時。當我投票時,它顯示「1票」。奇怪的。數據庫值和值顯示在視圖中的奇怪差異

這裏是在video_votes控制器的創建方法:

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 

爲什麼會發生這種情況,我該如何解決?

+0

如果你有這個名字的模型字段,你如何計算'Video'中的'vote_sum'?你應該切換到計算選票的唯一方式 - 現在你從'video_vote'' after_update'更新一次,然後在'Video.vote_sum'中重新計算 - 這可能是唯一的麻煩。 – mpapis 2011-03-20 00:17:55

+0

嗯,那我該如何解決? – 2011-03-20 00:22:34

+0

首先嚐試玩具從'Video'中刪除'def vote_sum',如果我得到了它的話,'Video.vote_sum'將在我的答案中正確更新。 – mpapis 2011-03-20 00:25:23

回答

0

我相信這是你的看法,你正在使用pluralize --you're應該通過它的名詞的單數版的方式有問題,並可選複數版本(如果它能夠」你猜對了)。請參閱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! 

你有你的Video模式叫vote_sum方法。這意味着當您訪問@video.vote_sum時,由於您覆蓋了該功能,因此您沒有從數據庫訪問模型中的vote_sum屬性。這使得在VideoVoteafter_create中更新vote_sum毫無意義,因爲您永遠無法訪問它(如上面我的IRB會話中所示)。

+0

謝謝!你很好 :) – 2011-03-20 01:45:06

0

你應該重新加載視頻:

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

可能有其他的方式來重新加載vote_sum只是沒重裝@video但這應該是相當足夠的起點。


同時請注意,你可以有一個更好的使用模式:counter_cache的時候,你會分開updown票分離的關係/模型......這是可悲的,但有時讓rails的完整能力,你需要做出怪異與你的模型的東西。

+0

我不明白,爲什麼我需要這樣做? – 2011-03-19 23:43:52

+0

導致你在更新它的'vote_sum'之前加載'@ video',當你想獲得當前的'vote_sum'你需要重新加載'@ video' – mpapis 2011-03-19 23:49:10

+0

這不能解決問題:/ – 2011-03-20 00:07:12