views:

23

answers:

3

Lets say Users have BankAccounts which have a balance value.

So, how do I generate an array that Users and the total value of all their BankAccounts' values added together?

A: 

First you need to find the users you want so I'll just assume you want all users.

@users = User.all

Then you need to take the array and collect it with only the elements you want.

@users.collect! {|u| [u.name, u.bank_account_total_value]}

For this kinda attribute I would set it in the model assuming you have has_many :transactions as an association

Class User

 has_many :transactions 

 def bank_account_total_value
     total = 0
     self.transactions.each do |t|
        total += t.amount
     end 
 end   

end 
Sam
It may be okay for this example (how many bank accounts will a person realistically have?) but in general it's a super bad idea to do calculations like this in Ruby code when you could do it in SQL.
Michael Melanson
+3  A: 

I'm not sure if this is quite what you want, but you can do something like:

ActiveRecord::Base.connection.select_all("select user_id, sum(balance) from accounts group by user_id;")

This will give you an array of user_ids and balances from the accounts table. The advantage of doing it this way is that it comes down to only one SQL query.

...and you don't end up retrieving the entire table. I don't know if that matters to you, but full table retrievals kill one of my apps and have to be avoided at all costs.
how do I put that into an arary or hash?
DerNalia
like, I putsed, and nothing showed up in the console
DerNalia
nvm, I was looking in the wrong spot. haha
DerNalia
+1  A: 

You'll want to do something like this. I don't believe it's possible to use #sum via an association.

class User
  def net_worth
    BankAccount.sum(:balance, :conditions => ["user_id = ?", self.id])
  end
end

Edit

I see a reference to a #sum in AssociationCollection, so try this:

class User
  def net_worth
    self.bank_accounts.sum(:balance)
  end
end

(I haven't tested this code)

Michael Melanson