【问题标题】:Rails getting the count from a deep associationRails 从深度关联中获取计数
【发布时间】:2018-12-17 12:01:43
【问题描述】:

我正在尝试计算从零售商产品中重定向的次数。最好的方法是什么?

我试过用:@products.includes(:retailer_products).includes(:redirects).count("redirects.id")}

我已经能够获得单个产品的计数,但我想获得基于所有产品的计数。

product 有一个retailer,而retailer products 又是retailer products。每个retailer product 都有redirects,其中包含retailer_product_id,以及它被点击的日期-created_at

注意:有些产品没有零售商产品,因此不会有任何关联的重定向。

产品型号

has_many :retailer_products
has_many :retailers, through: :retailer_products

零售商产品型号

has_many :redirects

重定向模型

belongs_to :retailer_product

【问题讨论】:

  • 所以您想要通过retailer_products 与特定产品相关的重定向数量,对吗?而RetailerProduct 属于project,对吧?
  • 没错。我已经能够获得单一产品的零售商产品,它只是所有产品的重定向计数。有些产品没有retailer_product。

标签: ruby-on-rails associations model-associations


【解决方案1】:

你为什么不试试另一种方式,毕竟你对Redirect计数感兴趣:

Redirect.joins(:retailer_product)
        .where(retailer_products: { product_id: @products.pluck(:id) })

【讨论】:

  • 该死,是的!干杯,你是一个救生员。这是一种享受。我没有这样想。
猜你喜欢
  • 2017-05-09
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多