Enner31
Enner31

Reputation: 203

Calculate the sum in an loop

I'm currently working on a rails project, I'm kinda newbie in this language. Using Devise, I want to have the sum of the sign_in_count and display it.

My sign_in_count is an integer and have a default value at 0, incrementing every time the user sign in.

here's what I've tried so far :

count_sign_in = 0

@users.each do |user|
  count_sign_in << user.sign_in_count 
end 

But as you can imagine, it doesn't work ... And I want to have the sum per week and per month if that's possible.

Any help ? Many thanks.

Upvotes: 0

Views: 1086

Answers (3)

mourad.hammiche
mourad.hammiche

Reputation: 1

As already answered above, the easiest way to do this is to use an sql aggregation.

User.sum(:sign_in_count)

You also perform a sum on a collection of object. In this case an #each iteration is not the optimale as it require an extra locale variable. The Enumerable module provides a bunch of useful methods like sum

@users.sum { |user| user.sign_in_count }

It can also be written shorten using a symbol to proc

@users.sum(&:sign_in_count)  

Upvotes: 0

Gagan Gami
Gagan Gami

Reputation: 10251

correct your code:

count_sign_in = 0

@users.each do |user|
  count_sign_in += user.sign_in_count # similar to count_sign_in = count_sign_in + user.sign_in_count
end

Note: count_sign_in is not an array, to push element in array we use << in ruby

Upvotes: 0

Ursus
Ursus

Reputation: 30056

I'd use a single SQL query

User.sum(:sign_in_count)

Upvotes: 3

Related Questions