简体   繁体   中英

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. 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') %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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