【发布时间】:2019-05-06 04:55:54
【问题描述】:
我有这三个模型:
class Order
has_many :items
end
class Item
belongs_to :order
belongs_to :product
end
class Product
has_many :orders, through: :items
has_many :items
end
我需要列出给定日期范围内每种产品的订单数量。
我可以获取某个日期范围内的所有订单:
Order.date_range(from, to)
现在我需要分组和计数;项目模型上有product_id 和units 字段。
我已经看到了解决方案,但只是在有两个表(订单>产品)而不是三个(订单>项目>产品)的情况下。
【问题讨论】:
-
你不能在 AREL 查找上调用 count 吗?这将在 sql 中执行并且应该是高性能的
-
我不知道。由于一些 Rails 弃用警告,我刚刚使用了 Arel。
-
对不起。我忘记了 arel 已合并到核心中。 arel 我的意思是 ActiveRecord_Relation 对象,即 Order.date_range(from, to).count
-
我尝试使用连接、包含等。但无法使其工作。
-
试试
Item.joins(:order).where(orders: {created_at: @from..@to}).group(:product_id).pluck('items.product_id, sum(items.units)')或者请提供想要的结果。
标签: ruby-on-rails postgresql activerecord