【发布时间】: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