[英]How to add sum of a field from joined model in Rails?
如何使用Rails 3.2和MySql 5.5从联接的模型中添加字段的总和?
假设我有这样的模型:
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>
(使用LEFT JOIN是获得相同结果的另一种方法。)
如何使用Rails做到这一点?
我想要这样的东西:
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(:account).where(<mycondition>).sum(:amount)
外地被求和amount
是在operations
表; 因此,活动记录查询也将在Operation
模型上进行。 mycondition
应该定义为包括属于特定帐户的操作。
如果即使没有操作记录,也需要执行LEFT JOIN
来检索帐户,则需要使用以下命令键入该连接条件:
totals = Account.where(<account conditions>).joins("LEFT JOIN operations ON operations.account_id = accounts.id AND operations.op_type = 'deposit'").group("accounts.number").sum(:amount)
totals.each do |a|
puts "Account #{a[0]} has deposited #{a[1]} total."
end
如果您愿意将此分为两个查询,则可以选择以下方法:
accounts = Account.where(<account conditions>)
totals = Operation.where(op_type: "deposit", account_id: accounts.map(&:id)).group(:account_id).sum(:amount)
accounts.each do |a|
puts "Account #{a.number} has deposited #{totals[a.id] || 0} total."
end
编辑:如果您需要帐户实例并需要按总和进行排序,则将开始引入一些其他SQL。但是类似这样的方法应该起作用:
accounts = Account.where(<account conditions>).joins("LEFT JOIN operations ON operations.account_id = accounts.id AND operations.op_type = 'deposit'").group("accounts.number").select("accounts.*, COALESCE(SUM(amount), 0) AS acct_total").order("acct_total")
accounts.each do |a|
puts "Account #{a.number} has deposited #{a.acct_total} total."
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.