Denis Davydov
Denis Davydov

Reputation: 462

Ruby on Rails, sum of an attribute of an attribute

I'm having some problems with my Ruby on Rails website. Let me explain. I have a user model, it has many credits

In order to count, the credits for a user I do:

@user.credits.sum(:score)

This works fine.

Now have a model team, that has many users, and I want to find out the total number of credits, I found on another StackOverflow post this:

array.inject{|sum,x| sum + x }

So I thought for me it should look like that:

@team.users.inject{|sum,x| sum + x.credits.sum(:score)}

But this returns

#<User:0x00000101a7c180>

instead of the sum. Guess I'm doing something wrong. Don't hesitate if you have an idea.

Thanks

Upvotes: 1

Views: 378

Answers (1)

xdazz
xdazz

Reputation: 160883

You have to set the initial value:

@team.users.inject(0){ |sum,x| sum + x.credits.sum(:score) }

You could also do:

@team.users.sum{ |x| x.credits.sum(:score) } 

Upvotes: 1

Related Questions