鉴于以下模型:
class PeriodBilling < ActiveRecord::Base
belongs_to :appcode
belongs_to :period
belongs_to :sla
belongs_to :unit_type
belongs_to :dpc_employee
belongs_to :general_ledger
end
class GeneralLedger < ActiveRecord::Base
has_many :appcodes
has_many :sla_task_details
belongs_to :expense_category
has_many :period_billings
has_many :expected_billings
end
如何在Rails中找到以下SQL等效项,以显示为左侧为句点的矩阵和顶部的general_ledgers,并在相应的字段中添加总和(pb.current_amt)?
select pb.pe_number, gl.general_ledger_number, sum(pb.current_amt)
from period_billings pb, general_ledgers gl
where pb.sla_id = 21
and pb.general_ledger_id = gl.id
group by pb.pe_number, gl.general_ledger_number
在Active Record中,这是我想要找到的东西:
@sla = Sla.find(params[:id])
@period_billings = PeriodBilling.where("sla_id = ?", @sla.id).group_by(&:general_ledger_id)
@billing_sum = @period_billings.inject(0){|sum,billing| sum+billing.current_amt}
所以,我想找到所选sla的所有period_billings,按general_ledger_id分组,得到这些记录的period_billing.current_amt的总和。然后,我想将12个时段放在一边,以在顶部的相应general_ledger列中显示总计金额。
提前致谢!!! :)
答案 0 :(得分:0)
对我建议的事情只是一个疯狂的小刺。有些东西更适合直接sql,当出现这种情况时,就像你要求的那样,最好只使用sql。
ActiveRecord::Base.connection.execute <<-EOF
select pb.pe_number, gl.general_ledger_number, sum(pb.current_amt)
from period_billings pb, general_ledgers gl
where pb.sla_id = 21
and pb.general_ledger_id = gl.id
group by pb.pe_number, gl.general_ledger_number
EOF