2017-06-22 21 views
0

我已經在rails中創建了一個基本的upvoting和downvoting系統。我有一個專欄,跟蹤upvotes和一個跟蹤downvotes。有沒有一種方法可以減去這些列(可能通過幫手)來顯示兩者之間的選票記錄?最好的方法來計算Rails中的兩列

我想這與助手:

module PostsHelper 
    def count_votes(up, down) 
    @total = (up-down) 
    return @total 
    end 
end 

Index.html.erb

<% @posts.each do |post| %> 
<div class="panel"> 
    <div class="panel-left"> 

    <%= link_to 'Upvote', upvote_post_path(post), method: :patch, remote: true %> 

    <%= link_to 'Downvote', downvote_post_path(post), method: :patch, remote: true %> 

    <%= count_votes(post.up_vote, post.down_vote) %> 

    <%= post.title %> 
    <%= post.content %> 
</div> 
</div> 

<% end %> 

但是,產生這樣的錯誤:

undefined method `-' for nil:NilClass 

有沒有做一個理想的方式這個?我應該在模型中使用某些東西嗎?

回答

1

您可以在模型中創建一個實例方法。例如:

# models/post.rb 

    def count_votes 
    (up || 0) - (down || 0) # "|| 0" because subtracting from `nil` will throw `nil:NilClass` error. 
    end 

現在您可以從視圖中調用post.count_votes以獲得所需的結果。

+0

太棒了!謝謝。所以你建議在模型中而不是幫助者中做這件事? – tfantina

+1

是的。它應該屬於模型。 –

1

似乎post.up_vote(和post.down_vote)列的默認值爲NULL。因此@total = (up-down)失敗。

您可以通過具有up_vote和默認值down_vote0

解決這個問題您可以在數據庫級別,添加這個由移民 指定default或者你可以在模型級別保持它,如果你不想要觸摸遷移, 例如:

# post.rb 
after_initialize :set_defaults 

def set_defaults 
    self.up_vote = 0 
    self.down_vote = 0 
end 
相關問題