Rails 4 嵌套 has_many 沿途有 where 子句

Rails 4 nested has_many with where clauses along the way

关系如下

Client -> has_many :analytics
Client -> has_many :metrics, through: :analytics
Analytic -> has_many :metrics

现在我不能简单地执行 Client.find(1).analytics.where(condition).metrics,因为我收到此错误:

undefined method `metrics' for #<Analytic::ActiveRecord_AssociationRelation:0x00000002e31a50>

我发现我可以做的是以下内容,但它看起来很笨重,而且不是 rails 的方式:

analytics = client.analytics.where(conditions).select(:id)
metrics = Metric.where(analytic_id: analytics)

有没有办法像我上面描述的那样以更明智的方式将其链接在一起?

最终,你似乎想要metrics,所以你应该从这里开始。

你还需要查询关联的条件。

并加入协会查询您的条件

尝试这样的事情:

metrics = Metric.joins(analytic: [:client]).where(analytic:{ conditions, client_id: client })

编辑

我认为我们可以使查询更优雅。

让我知道这是否有效,在这里让我头疼。

client = Client.find(1)
metrics = client.metrics.joins(:analytic).where(analytics: {conditions})