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"
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