MikeHolford
MikeHolford

Reputation: 1931

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?

Upvotes: 0

Views: 123

Answers (1)

Jon
Jon

Reputation: 10898

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

Upvotes: 3

Related Questions