J3RN J3RN - 11 days ago 6
Ruby Question

Rails 4 Sum by Model Method

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
that might be
User
or an
ActiveRecord::Relation
of
users
, and I would like to sum all of the
@users
's
goal_ytd
s.

My first inclination was:

@users.sum(&:goal_ytd)


Which threw a deprecation warning in both cases because using
sum
on an
ActiveRecord::Relation
is going away in Rails 4.1.

So, I changed the code to:

@users.to_a.sum(&:goal_ytd)


Which then threw a
NoMethodError
because, in a certain circumstance,
@users
is assigned by
@users = User
and
User
has no
to_a
method.

Assigning
@users
using
@users = User.all
throws a deprecation warning because
Relation#all
is also deprecated.

Is there a way to get all
Users
as an array? Is there a better way?

Answer

On Rails 4.1

If goal_ydt is a column in the users table:

@users.sum(:goal_ydt)

If goal_ydt is a method in User class:

@users.to_a.sum(&:goal_ydt)
Comments