我已經在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
有沒有做一個理想的方式這個?我應該在模型中使用某些東西嗎?
太棒了!謝謝。所以你建議在模型中而不是幫助者中做這件事? – tfantina
是的。它應該屬於模型。 –