Rails 4 Sum by Model Method

后端 未结 4 1220
夕颜
夕颜 2021-02-13 02:07

In my app, I have a User model, with a goal_ytd method, which performs some calculations.

In a controller, I have a variable @users

4条回答
  •  一个人的身影
    2021-02-13 03:10

    You should not use enumerable methods here. Use sum which is defined on ActiveRecord::Relation and takes symbol as parameter. The main difference is that it will perform SUM query in your database, so it is much faster than pulling all the records form db. Also if any of your record has blank value for given field, enumerable sum will throw an error, while ActiveRecord's one will not. In short:

    @users.sum(:goal_ydt)  
    

    EDIT:

    However since goal_ydt is not a field but a method, you have no choice but to loop over the models. The way I usually do this is by using scoped method:

    @users.scoped.sum(&:goal_ydt)
    

提交回复
热议问题