减去 ruby 个变量,这些变量是活动记录对象关联的计数
Subtracting ruby variables which are the count of an active record object association
我有一个供作者和书评人使用的应用程序。最近我完成了一项功能,版主可以将评论投票为有帮助或无帮助,这决定了评论者的分数(以检查他们的评论)。我有一个评论模型,其中 not_helpful 作为 table 上的布尔列默认设置为 false。当主持人单击评论上的 link 时,显示它是否有帮助,然后将该评论记录的布尔值更新为 true。我正在尝试在该评论者的个人资料上建立一个记分卡,我使用数学从用户的总评论数中减去 non_helpful 评论,然后将该总和除以总评论数得出一个百分比那个审稿人的分数。从本质上讲,当他们的评论没有帮助时,这就是对他们的标记,就像在测试中出错一样。因此,在所有评论中,我们想从总评论中减去所有无用的评论,然后将得到的答案除以总评论,得到他们的分数。到目前为止我有这个:
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>
我以前从未用运算符做过简单的 ruby 数学运算,也没有为活动记录对象设置变量并调用它们,那么正确的做法是什么?现在用户分数是 0%,这不对,因为我登录的当前评论者总共有 4 条评论,2 条有帮助,2 条没有帮助,根据评分系统我应该给他们 50% 的分数。我正在努力实现
叫做"integer division"。当两个操作数都是整数时,结果也是。所以要么使 one/both 操作数浮动
@score = subtotal.to_f / total
或使用fdiv
@score = subtotal.fdiv(total)
我有一个供作者和书评人使用的应用程序。最近我完成了一项功能,版主可以将评论投票为有帮助或无帮助,这决定了评论者的分数(以检查他们的评论)。我有一个评论模型,其中 not_helpful 作为 table 上的布尔列默认设置为 false。当主持人单击评论上的 link 时,显示它是否有帮助,然后将该评论记录的布尔值更新为 true。我正在尝试在该评论者的个人资料上建立一个记分卡,我使用数学从用户的总评论数中减去 non_helpful 评论,然后将该总和除以总评论数得出一个百分比那个审稿人的分数。从本质上讲,当他们的评论没有帮助时,这就是对他们的标记,就像在测试中出错一样。因此,在所有评论中,我们想从总评论中减去所有无用的评论,然后将得到的答案除以总评论,得到他们的分数。到目前为止我有这个:
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>
我以前从未用运算符做过简单的 ruby 数学运算,也没有为活动记录对象设置变量并调用它们,那么正确的做法是什么?现在用户分数是 0%,这不对,因为我登录的当前评论者总共有 4 条评论,2 条有帮助,2 条没有帮助,根据评分系统我应该给他们 50% 的分数。我正在努力实现
叫做"integer division"。当两个操作数都是整数时,结果也是。所以要么使 one/both 操作数浮动
@score = subtotal.to_f / total
或使用fdiv
@score = subtotal.fdiv(total)