具有三级深度连接的作用域 [英] Scope that has three levels deep joins
问题描述
我的Program
表有很多Measures
我的 Measure
表有很多 Targets
我的 Target
表有一列名为money"
My Program
table has many Measures
My Measure
table has many Targets
My Target
table has a column called "money"
我的 ActiveRecord 查询如下所示:
My ActiveRecord query looks like this:
@programs2 = Program.includes([measures: :target]).where('organization_id = 1').limit(2)
我想定义一个范围,以便查询可以返回其 target.money 值最低的顶级程序.因此,我需要编写一个范围并将其应用于该查询,但是我应该如何以及在模型中的何处定义该范围,像这样?好吧,这行不通,但我知道的就这么多.
I want to define a scope such that the query can return top Programs that their target.money value is the lowest. So I need to write a scope and apply it to that query but How and Where in the model should I define that scope, something like this? Well this won't work but that's as much as I know.
scope :top5, :joins => [:measures, :targets] , :order => "money DESC"
推荐答案
一个 Program 的 target.money 是多少,这个 Program 的所有 Measures 的所有 Targets.money 的总和?
What is the target.money of a Program, the sum of all Targets.money of all Measures for this Program ?
您可以尝试以下操作:
Target.order_by( :money => :desc ).map{|target| target.measure }.map{|measure| measure.program }.uniq
祝你好运
这篇关于具有三级深度连接的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!