Search code examples
ruby-on-railsrails-activerecord

Rails sum column only if boolean is true


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?


Solution

  • 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)
    # --------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^