如何根据 rails 中的某些条件准备结果

How to prepare result based on certain conditions in rails

我有以下3种模式(订单、保险、捐赠)。

 #order.rb
has_one :donations 
has_one :insurances

 #insurance.rb
belongs_to :order

 #donation.rb
belongs_to :order

现在我各自的表包含以下数据:

 #Order
id customer_id  delivery_status  price 
1    10          true            50
2    10          true            60
3    10          false           70
4    10          false           80
5    10          true            90
6    10          true            10

 #insurance
id token  order_id
1   ABC     3

 #donation
id  amount order_id
1      10    4

现在,我需要为每个客户准备最终报告,其中包括他们的 ID、已交付物品的总价、未交付物品的总价、金额(来自捐赠)、代币(来自保险)。

在最终结果中,我需要这样的东西:

customer_id  total_price_of_delivered  total_price_of_undelivered amount token
1             50+60+90+10=250                  150            10    ABC
2             xxxx                             xxx           XXX      XXX

目前我正在尝试使用以下代码库:

result = Order.includes(:insurance, :donation)

delivered_items_price = 0 
undelivered_items_price = 0 
result.each do |order| 
 customer_id = order.customer_id 
  # will loop through all orders based on conditions. 
  #then put the fetched result in an array of hash. 
end

对于这个问题,我们有更好的 alternative/solution 吗?

让我们按照 Arel 的方式来做。我将通过 Arel 文档中的代码片段向您概述必须完成的工作,而不是可运行的代码。

  1. 我们将使用 arel_table 来创建我们的查询。对于名为 Order 的模型,获得 Arel table 就像 orders = Order.arel_table
  2. 一样简单
  3. 获取列的总和并结合分组就像 orders.project(orders[:price].count).group(users[:delivery_status])。请注意,您需要先按 customer 分组,然后再按 delivery_status.
  4. 由于我们需要在最终结果中有多个总和,因此您需要使用 Common Table Expressions(CTE). Take a look at docs and this answer 了解更多信息。
  5. 最后,您会将结果与其他 table 合并。例如。 orders.join(insurances).on(YOUR_CONDITIONS)