如何使用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