如何使用Rails 3.2和MySql 5.5添加來自加入模型的字段的總和?如何在Rails中添加加入模型的字段總和?
比方說,我有模型是這樣的:
class Account < ActiveRecord::Base
attr_accessible :number
has_many :operations
end
class Operation < ActiveRecord::Base
belongs_to :account
attr_accessible :op_type, # either 'deposit' or 'withdrawal'
:amount
end
我需要使用一些條件來選擇帳戶,並添加到所有存款帳戶的每個人的總和。
這可以通過SQL就像這樣:
SELECT *,
IFNULL((
SELECT SUM(amount)
FROM operations
WHERE operations.account_id = accounts.id AND operations.op_type = 'deposit'
), 0) as total_deposits
FROM accounts
WHERE <condition for accounts>
我怎樣才能做到這一點使用Rails(使用LEFT JOIN另一種方式來達到同樣的效果。)?
我想是這樣的:
accounts = Account.where(<mycondition>). join(???). sum(???) # What should be here?
accounts.each do |a|
puts "Account #{a.number} has deposited #{a.total_deposits} total."
end
'Operation.joins(:帳戶)'不工作,因爲它沒有返回有沒有存款記錄尚未賬戶。 我需要結果集中的這些帳戶。 total_deposits應該爲0。 – 2014-12-13 03:52:13