【发布时间】:2020-06-12 20:36:00
【问题描述】:
这里是新开发者。
我有一个customer_controller.rb,它收集所有已完成的订单并通过电子邮件地址对它们进行分组以获取我们的“客户”列表。
客户控制器:
class CustomerController < ApplicationController
def index
orders = Spree::Order.where(completed_at: from...to)
@customers = orders.group_by(&:email)
end
end
我有这样的视图模板:
<% @customers.each_pair do |email, orders| %>
<% total_orders = Spree::Order.where(state: "complete", email: email) %>
<% arr = orders %>
<% amount = arr.inject(0) {|sum, hash| sum + hash[:payment_total]} %>
<tbody id="tbodyid">
<tr>
<td><%= email %></td>
<th><%= orders.count %></td>
<td><%= total_orders.count %></td>
<td><%= total_orders.first.completed_at.strftime("%D") if total_orders.first.completed_at.present? %></td>
<td>$<%= amount %></td>
</tr>
</tbody>
<% end %>
为此处理模型的最佳方法是什么?将这种逻辑放在视图中是服务器的噩梦。我想要一个基于@customers 实例的模型,但我不知道该怎么做。
我是否完全放弃这个方向并修改order_decorator.rb 模型以获取客户集合?
编辑:针对以下问题,这里有一个 Spree::Order 记录。所有订单都有电子邮件,并非所有订单都有 user_id。
#<Spree::Order id: 334, number: "R826173067", item_total: #<BigDecimal:7f9ee91516b8,'0.2198E2',18(18)>, total: #<BigDecimal:7f9ee91515f0,'0.1999E2',18(18)>, state: "complete", adjustment_total: #<BigDecimal:7f9ee91514b0,'-0.199E1',18(18)>, user_id: 45, completed_at: "2020-06-10 15:43:35", bill_address_id: 243, ship_address_id: 244, payment_total: #<BigDecimal:7f9ee9150e20,'0.1999E2',18(18)>, shipping_method_id: nil, shipment_state: "partial", payment_state: "paid", email: "bobby@boby.com", special_instructions: nil, created_at: "2020-06-10 15:42:28", updated_at: "2020-06-10 15:43:35", currency: "USD", last_ip_address: "127.0.0.1", created_by_id: 45, shipment_total: #<BigDecimal:7f9ee91500d8,'0.0',9(18)>, additional_tax_total: #<BigDecimal:7f9ee9150010,'0.0',9(18)>, promo_total: #<BigDecimal:7f9edd683ef8,'-0.199E1',18(18)>, channel: "spree", included_tax_total: #<BigDecimal:7f9edd683db8,'0.0',9(18)>, item_count: 2, approver_id: nil, approved_at: nil, confirmation_delivered: true, considered_risky: false, express: false, source: nil, purchased_via_subscription: false>
【问题讨论】:
-
不熟悉 Spree,你能发布一下
orders = Spree::Order.where(state: "complete")的单条记录吗?还有你的客户模型代码是什么样的? -
我现在根本没有客户模型。所有的“逻辑”都在可怕的视图模板中处理。我将在上面的原始帖子中发布一条记录。谢谢
-
你能解释一下
orders.count和total_orders.count吗?对我来说看起来一样。amount也只是用户完成订单的“payment_total”总和吗? -
total_orders.first.completed_at...也应该是 created_at 的第一个订单吗?你确定你的total_orders数组是由 created_at 排序的吗?该字段到底应该代表什么? -
@Beartech 很抱歉造成混淆,请参阅上面控制器中的编辑(我最初是为了简单起见进行编辑)。我从给定时间(从...到)内的订单收集电子邮件,然后有两列:一列是在时间范围内完成的订单,一列是终身订单。
标签: ruby-on-rails postgresql spree