Ruby on rails 即使第二个表中的字段可能为空,如何对两个表中的两个字段求和?
我有以下表格: 产品。rbRuby on rails 即使第二个表中的字段可能为空,如何对两个表中的两个字段求和?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我有以下表格: 产品。rb # has_many :sales +----+----------+----------+-------+ | id | name | quantity | price | +----+----------+----------+-------+ | 1 | Pencil | 30 | 1.0 | | 2 | Pen | 50 | 1.5 | | 3 | Notebook | 100
# has_many :sales
+----+----------+----------+-------+
| id | name | quantity | price |
+----+----------+----------+-------+
| 1 | Pencil | 30 | 1.0 |
| 2 | Pen | 50 | 1.5 |
| 3 | Notebook | 100 | 2.0 |
+----+----------+----------+-------+
# belongs_to :product
+----+----------+------------+
| id | quantity | product_id |
+----+----------+------------+
| 1 | 10 | 1 |
| 2 | 2 | 1 |
| 3 | 5 | 1 |
| 4 | 2 | 2 |
| 5 | 10 | 2 |
+----+----------+------------+
sales.rb
# has_many :sales
+----+----------+----------+-------+
| id | name | quantity | price |
+----+----------+----------+-------+
| 1 | Pencil | 30 | 1.0 |
| 2 | Pen | 50 | 1.5 |
| 3 | Notebook | 100 | 2.0 |
+----+----------+----------+-------+
# belongs_to :product
+----+----------+------------+
| id | quantity | product_id |
+----+----------+------------+
| 1 | 10 | 1 |
| 2 | 2 | 1 |
| 3 | 5 | 1 |
| 4 | 2 | 2 |
| 5 | 10 | 2 |
+----+----------+------------+
首先,我想知道我还剩下多少东西,不管它们是什么类型的。答案当然是151,但那就是作弊。我可以简单地分别对两个表求和,然后将它们放在一起以知道最终的数字,但我想知道是否可以通过activerecord在一个命令中完成这项工作
我尝试了以下方法:
Product.includes(:sales).group('products.id').sum('products.quantity - sales.quantity')
但我得到:
=> {1=>73, 2=>88, 3=>0}
这是可以理解的,因为它是通过每一个这样做的总和:
+-------------------+----------------+-----+
| products.quantity | sales.quantity | sum |
+-------------------+----------------+-----+
| 30 | 10 | 20 |
| 30 | 2 | 28 |
| 30 | 5 | 25 |
+-------------------+----------------+-----+
等于73
无论如何,ActiveRecord如何实现这一点?我想知道项目的总数,但我也想知道每种类型的总数。我不熟悉任何
ActiveRecord
方法来实现您想要的,但您可以尝试在其中混合一些sql
Product
.group('products.id')
.sum('products.quantity - (SELECT SUM(sales.quantity) AS sales_quantity FROM sales WHERE sales.product_id = products.id)')