0

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?

1
  • Are you saying a user has many bank_accounts?
    – Skilldrick
    Aug 19, 2010 at 21:07

3 Answers 3

3

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.

2
  • ...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. Aug 19, 2010 at 21:15
  • how do I put that into an arary or hash? Aug 20, 2010 at 15:04
1

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)

0
0

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 
1
  • 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. Aug 19, 2010 at 21:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.