Home > Software engineering >  Rails sum column only if boolean is true
Rails sum column only if boolean is true

Time:11-20

I have the following call to sum a users points for challenges:

 @points = current_user.challenges.sum(:xp)

On the challenges model there is an accomplished boolean. I want to sum the points for only the challenges belonging to the user that have the accomplished boolean true. How do I do that exactly in this call?

CodePudding user response:

current_user.challenges is a relation so you can add more where calls to filter the results and then sum that:

@points = current_user.challenges.where(accomplished: true).sum(:xp)
# --------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^
  • Related