我会从头开始解释我的疑问。我有以下表格:
carts
+----+-------------------------+-------------------------+
| id | created_at | updated_at |
+----+-------------------------+-------------------------+
| 1 | 2013-11-09 12:57:37 UTC | 2013-11-09 12:57:37 UTC |
| 2 | 2013-11-10 11:33:25 UTC | 2013-11-10 11:33:25 UTC |
| 3 | 2013-11-10 12:16:25 UTC | 2013-11-10 12:16:25 UTC |
+----+-------------------------+-------------------------+
line_items
+----+------------+---------+-------------------------+-------------------------+----------+
| id | product_id | cart_id | created_at | updated_at | quantity |
+----+------------+---------+-------------------------+-------------------------+----------+
| 1 | 2 | 2 | 2013-11-10 11:33:25 UTC | 2013-11-10 11:33:25 UTC | 1 |
| 2 | 2 | 2 | 2013-11-10 11:45:26 UTC | 2013-11-10 11:45:26 UTC | 1 |
| 3 | 5 | 2 | 2013-11-10 11:46:06 UTC | 2013-11-10 11:46:06 UTC | 1 |
| 4 | 2 | 2 | 2013-11-10 12:08:41 UTC | 2013-11-10 12:08:41 UTC | 1 |
| 5 | 5 | 2 | 2013-11-10 12:09:03 UTC | 2013-11-10 12:09:03 UTC | 1 |
| 6 | 5 | 2 | 2013-11-10 12:15:48 UTC | 2013-11-10 12:15:48 UTC | 1 |
| 7 | 2 | 3 | 2013-11-10 12:16:26 UTC | 2013-11-10 12:16:26 UTC | 1 |
| 8 | 2 | 3 | 2013-11-10 12:29:21 UTC | 2013-11-10 12:29:21 UTC | 1 |
+----+------------+---------+-------------------------+-------------------------+----------+
我执行以下语句:
cart = Cart.find(2)
sums = cart.line_items.group(:product_id).sum(:quantity)
结果如下:=> {2=>3, 5=>3}
直到这里我不得不说这在我看来很清楚,即我根据产品 id 计算产品的总和,然后我折叠相同的产品。
后来出现了疑问,当我试图分解指令时,cart.line_items.group(:product_id).sum(:quantity)
我遵循了以下步骤:
cart = Cart.find(2)
items = cart.line_items.group(:product_id)
我得到了:
+----+------------+---------+-------------------------+-------------------------+----------+
| id | product_id | cart_id | created_at | updated_at | quantity |
+----+------------+---------+-------------------------+-------------------------+----------+
| 4 | 2 | 2 | 2013-11-10 12:08:41 UTC | 2013-11-10 12:08:41 UTC | 1 |
| 6 | 5 | 2 | 2013-11-10 12:15:48 UTC | 2013-11-10 12:15:48 UTC | 1 |
+----+------------+---------+-------------------------+-------------------------+----------+
最后我执行items.sum(:quantity)
了,在这里,令我惊讶的是,我再次感到=> {2=>3, 5=>3}
怀疑,因为我不明白如果我sum
对items
包含只有 2 行,每行的数量为 1。
记住什么
?items
从cart.line_items.group(:product_id)
or 和 SQL 字符串中获得的对象意味着每次我items
与我的数据库交互时都与我交互?我有点困惑。