Rails 4嵌套has_many,其中包含where子句

时间:2016-12-08 16:53:46

标签: ruby-on-rails activerecord rails-activerecord has-many-through

关系如下。

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>

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

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

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

1 个答案:

答案 0 :(得分:0)

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

您还需要查询关联条件。

加入协会查询您的情况。

尝试这样的事情:

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

修改

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

让我知道这是否有效,在这里脱离我的头脑。

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