【发布时间】:2014-12-13 02:50:24
【问题描述】:
如何使用 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
【问题讨论】:
标签: mysql ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2