1

我会从头开始解释我的疑问。我有以下表格:

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}
怀疑,因为我不明白如果我sumitems包含只有 2 行,每行的数量为 1。 记住什么
itemscart.line_items.group(:product_id)or 和 SQL 字符串中获得的对象意味着每次我items与我的数据库交互时都与我交互?我有点困惑。

4

1 回答 1

3

好问题。:-)

itemsActiveRecord::Relation代表查询的一个。并非对该对象的所有操作都会导致另一个数据库操作,但有些会。例如,length不要to_a再次访问数据库,但count会。

关系也是“可链接的”,所以当你调用items.sum(:quantity)它时,它会建立一个的关系。换句话说,一个关系既可以被认为是一个查询,也可以被认为是执行该查询的结果。当您链接方法时,您实际上是在查询组件上操作,而不是中间结果。

于 2013-11-10T15:28:45.170 回答