Rails 4 Sum by Model Method

后端 未结 4 1211
夕颜
夕颜 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 02:59

    The issue here is rooted in a fundamental misunderstanding of the Relation#all deprecation. While Relation#all is deprecated, Model#all is not. Therefore:

    @users = User.all
    

    is still perfectly valid, while:

    @users = User.where(first_name: "Mike").all
    

    is deprecated.

    So the end solution looks like:

    @users = User.all
    unless current_user.admin?
      @users = @users.where(company_id: current_user.company_id)
    end
    @users.to_a.sum(&:goal_ytd)
    

    A new question would be: How do I sum all the users goals, preferably in one line, without loading them all into memory? I suppose that's for another day.

提交回复
热议问题