bwobst
bwobst

Reputation: 351

Rails count number data within several records

I have a column in my database, "occurrences". The user has the option to enter nothing or any number from 1 to 10. And I'm trying to add all the occurrences (across several records) for each user into a grand total.

Part 1 - Filtering data to current user

@total_occurrences = Event.where(['occurrences <> ?', current_user.id])

So far so good.

Part 2 - Counting numbers in column "occurrences"

Not sure how to approach this...

Upvotes: 0

Views: 85

Answers (3)

Kindoloki
Kindoloki

Reputation: 614

If you use rails 4 you can write:

@total_occurrences = Event.where(user_id: current_user.id).where.not(occurrences: nil)

In rails 3 you can write sql query:

@total_occurrences = Event.where(user_id: current_user.id).where("occurrences IS NOT NULL")

Or use gem Squeel. It allows you to write like this:

@total_occurrences = Event.where{(user_id == current_user.id) & (occurrences != nil)}

Upvotes: 1

bwobst
bwobst

Reputation: 351

brendanjcaffrey's answer is what I'm looking for:

Event.where(user_id: current_user.id).where('occurrences <> 0').pluck(:occurrences).sum

Upvotes: -1

brendanjcaffrey
brendanjcaffrey

Reputation: 131

As for part two, you can do something like this:

sum = 0
Event.where(user_id: current_user.id).pluck(:occurrences).each do |occurrence|
  sum += occurrences
end

Pluck pulls out all the values of a specific column, then all you have to do is add them together.

Upvotes: 1

Related Questions