Calculate method is gone once I use 'find'?

Could someone please explain why this works:

current_user.accounts.sum(:balance)

But not this:

current_user.accounts.find_all_by_active(true).sum(:balance)

For the latter Rails tells me sum is an undefined method. It seems like
I lose the ActiveRecord methods when I call ‘find’?

This (simpler) does not work either:

current_user.accounts.find_all.sum(:balance)

Thanks!

One way:

Account.sum(:balance, :conditions => “user_id = #{current_user.id} AND
active = true”)

another way:

Account.with_scope(:find => “user_id = #{current_user.id} AND active =
true”) do
Account.sum(:balance)
end

Carl J. wrote:

This (simpler) does not work either:

current_user.accounts.find_all.sum(:balance)

In the first case, you are calling the sum method on an ActiveRecord
object.

In the second case, you are calling sum on an array of ActiveRecord
objects and as the error message tells you, the sum method is not
defined for Array objects.

The missing piece that you need to know is that when the finders return
more than one ActiveRecord the results are returned in an array of
ActiveRecords.

You should be able to rewrite your first query

current_user.accounts.sum(:balance, :conditions => [‘active == ?’,
true])

Ray

Thanks, that helps!

You should be able to rewrite your first query

current_user.accounts.sum(:balance, :conditions => [‘active == ?’,
true])

One question - where would be the best place for the above as far as MVC
goes? Directly in the view or should I be setting a variable to the
above in the controller?