使用rails查询返回计算值

时间:2018-02-02 12:43:19

标签: ruby-on-rails ruby-on-rails-4

我有一个问题:

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的总和。如何在数组中返回?

1 个答案:

答案 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查询解决方案

或者,如果您实际上希望将此值作为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