Writing scope, join and order for a Model

2019-09-06 17:17发布

问题:

My model is like this:

Program has_many Measures and then Measures has_many Targets and Target table has a column named value

My query is like this:

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

I don't know where or how to write the some_scope part of the query. The query starts with Program.includes so I think it should be defined in the Program model but the problem I have is that measures: :targets . How do I define a join for them. If it was just one table I know I can do like this:

scope :salary, :joins => :registry,   :order => "money DESC"

I need something similar for this one too, but this has has two tables like I explained above. I don't know how to write that one.

回答1:

Try,

scope :some_scope, joins(mesures: :targets)