我有一个问题:
php cron.php checkcron
返回@clients = Client.where(location_id: location).includes(:check_ins, :payments, :purchases).where("check_ins.created_at > ?", start_date).references(:check_ins)
的{{1}}数组。每个客户ActiveRecord::Relation
和每笔付款都有clients
。
对于has_many :payments
中的每位客户,我希望包含其付款金额:amount
的总和。如何在数组中返回?
答案 0 :(得分:1)
您可以随时编写辅助方法:
class Client
has_many: payments
def total_payment_amount
payments.sum(:amount)
end
end
然后在你给定的代码中,你可以像下面这样称呼它,或者你可以称之为它(例如在视图中):
@clients = Client.where(location_id: location).includes(:check_ins, :payments, :purchases).where("check_ins.created_at > ?", start_date).references(:check_ins)
@clients.each do |client|
puts client.total_payment_amount
end
或者,如果您实际上希望将此值作为SQL的一部分,以便您甚至可以进一步查询:
class Client < ApplicationRecord
has_many :payments
end
然后在你给定的代码中:
@clients = Client.select('SUM(payments.amount) AS total_payment_amount').joins(:payments)
@clients.each do |client|
puts client.total_payment_amount
end