Scope that has three levels deep joins

廉价感情. 提交于 2019-12-02 20:52:54

问题


My Program table has many Measures My Measure table has many Targets My Target table has a column called "money"

My ActiveRecord query looks like this:

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

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"

回答1:


What is the target.money of a Program, the sum of all Targets.money of all Measures for this Program ?

You can try something like:

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

Good luck



来源:https://stackoverflow.com/questions/15183785/scope-that-has-three-levels-deep-joins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!