【问题标题】:Rails 4 nested has_many with where clauses along the wayRails 4嵌套了has_many和where子句
【发布时间】:2016-12-08 16:53:45
【问题描述】:

关系如下。

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)

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

【问题讨论】:

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


    【解决方案1】:

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

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

    并加入协会以查询您的条件。

    试试这样的:

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

    编辑

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

    如果这行得通,请告诉我。

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

    【讨论】:

    • 谢谢。并不比我之前尝试过的更优雅,但绝对更具可读性。这两种解决方案都会导致 2 个 SQL 操作(我的一个 select 和一个 where in select 和你的一个 select 和一个 join。
    • 感谢has_many through 关联,您甚至不需要加入客户端。 c = Client.find(1) 就足够了 m = c.metrics.joins(:analytic).where(analytics: {cond})
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 2016-10-06
    • 2016-02-03
    • 2021-07-05
    • 1970-01-01
    相关资源
    最近更新 更多