减去作为活动记录对象关联计数的红宝石变量

时间:2018-10-12 17:56:41

标签: ruby-on-rails ruby variables math operators

我有一个面向作者和书评人的应用程序。最近,我完成了一个功能,主持人可以对评论进行投票,将其投票为有帮助或无用,它决定了评论者的得分(以确保对其评论进行检查)。我有一个回顾模型,其中表上的布尔列默认设置为false,它具有乐于助人和not_helpful。当主持人单击评论上的链接时,显示是否有用,然后将该评论记录的布尔值更新为true。我正在尝试在该评论者的个人资料上建立一个计分卡,在其中我使用数学从用户的总评论数中减去无帮助的评论,然后将该总和除以总评论数得出该评论者分数的百分比。从本质上讲,当他们的评论没有帮助时,这是对他们的标记,这就像在测试中弄错了一个问题。因此,在所有评论中,我们要从总评论中减去所有无用评论,然后得到答案,然后将其除以总评论即可得到其得分。到目前为止,我有这个:

users_controller.rb

def profile
    @current_user = current_user
    @helpful = current_user.reviews.where(helpful: true)
    @unhelpful = current_user.reviews.where(unhelpful: true)
    @reviews = current_user.reviews
    unhelpful = @unhelpful.count
    total = @reviews.count
    subtotal = total - unhelpful
    @score = subtotal / total  

  end

profile.html.erb

欢迎评论者,

<h2>How I'm doing</h3>

<table>
  <th>Total Reviews</th>
  <th>Helpful Reviews</th>
  <th>Unhelpful Reviews</th>
  <th>Score</th>
  <tr>
    <td><%= current_user.reviews.count %></td>
    <td><%= @helpful.count %></td>
    <td><%= @unhelpful.count %></td>
    <td><%= number_to_percentage(@score * 100, precision: 0) 
%></td>
  </tr>
</table>

我以前从未使用运算符和将变量设置为活动记录对象并对其进行调用来完成simpe ruby​​数学,那么正确的方法是什么?现在,用户分数是0%,这是不正确的,因为我登录的当前审阅者共有4条评论,2条有帮助和2条无用,根据我的评分系统,他们的得分为50%我试图实现

1 个答案:

答案 0 :(得分:1)

它称为“整数除法”。当两个操作数都是整数时,结果也将是。所以要么让一个/两个操作数都浮起来

@score = subtotal.to_f / total

或使用fdiv

@score = subtotal.fdiv(total)