【问题标题】:How to prepare result based on certain conditions in rails如何根据rails中的某些条件准备结果
【发布时间】:2015-02-02 10:42:31
【问题描述】:

我有以下 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

对于这个问题,我们有更好的替代方案/解决方案吗?

【问题讨论】:

  • 我会先根据送货状态对orders 进行分组,然后得到一个价格总和,然后加入其他表。当然,所有这些都在 SQL 中(使用 ActiveRecord 或 Arel)。

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


【解决方案1】:

让我们以Arel 的方式进行。我将用 Arel 文档中的代码 sn-ps 为您提供必须做的事情的大纲,而不是可运行的代码。

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

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多