简体   繁体   English

计算嵌入式红宝石中的值

[英]counting values in embedded ruby

Quick fire question. 快速射击问题。

If I have a list of values and I wan't to find the total and display it in embedded ruby, how would I go about this. 如果我有一个值列表,而又不想找到总数并将其显示在嵌入式红宝石中,那我将如何处理。

<% @user.recipes.each do |i| %>
  <% i.awards.each do |k| %>
    <%= k.points %>
  <% end %>
<% end %>

This renders: 这将呈现:

1 10 5 5 10 1 5 10 5 1 

with each number (1, 5 or 10) being a value from the database. 每个数字(1、5或10)都是数据库中的值。 Is there any way to get a count of this? 有什么办法可以计数吗? Or would it be better to create a seperate method in the controller to work this out? 还是在控制器中创建一个单独的方法来解决这个问题会更好?

<%= i.awards.sum(:points) %>

For for the sum of all points from all recipes: 对于所有配方中所有点的总和:

<%= @user.recipes.map { |r| r.awards.sum(:points) }.sum %>

Although it might be sensible to do this calculation within the model. 尽管在模型中进行此计算可能是明智的。 You'll remove a lot of duplication that way if you use it in more than one view. 如果您在多个视图中使用重复项,将会以这种方式删除大量重复项。

UPDATE: 更新:

As per the comments below, you could also ask the DB to calculate the sum for you: 根据以下评论,您还可以要求数据库为您计算总和:

<%= @user.recipes.joins(:awards).sum('awards.points') %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM