【问题标题】:Scope that has three levels deep joins具有三层深度连接的范围
【发布时间】:2013-03-03 08:18:14
【问题描述】:

我的Program 表有很多Measures 我的Measure 表有很多Targets 我的Target 表有一个名为“money”的列

我的 ActiveRecord 查询如下所示:

@programs2 = Program.includes([measures: :target]).where('organization_id = 1').limit(2)

我想定义一个范围,以便查询可以返回其 target.money 值最低的顶级程序。所以我需要编写一个范围并将其应用于该查询,但是我应该如何以及在模型中的何处定义该范围,像这样?好吧,这行不通,但我知道的就这么多。

scope :top5, :joins => [:measures, :targets]  ,  :order => "money DESC"

【问题讨论】:

    标签: ruby ruby-on-rails-3.2 rails-activerecord


    【解决方案1】:

    什么是 Program 的 target.money,该 Program 的所有措施的所有 Targets.money 的总和?

    你可以试试这样的:

    Target.order_by( :money => :desc ).map{|target| target.measure }.map{|measure| measure.program }.uniq
    

    祝你好运

    【讨论】:

    • target.money : 不,它只是一个数字,我为在 SO 上发布了一些表和字段名称,所以它们在实践中可能没有多大意义。
    猜你喜欢
    • 2013-02-06
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2012-10-03
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多