Bohn
Bohn

Reputation: 26919

Add "order" to a scope defined in the model

In my Test.rb model I have a scope like this:

#....
has_many fathers
scope :msr, includes(fathers: :kids)

the kids table/model its self let's say has a column named finger

and in the controller I am using my query like this:

 @tests = Test.msr.where(organization_id: params[:id]).limit(3)

I want to add a "order" clause so I can sort by the number of fingers each kid has. But not sure where and how can I add that "order" clause?

Upvotes: 0

Views: 200

Answers (1)

jvnill
jvnill

Reputation: 29599

try

scope :ordered_by_kid_fingers, order('kids.fingers DESC')

this is assuming that you load the associations through joins or includes so

>> Test.joins(fathers: :kids).ordered_by_kid_fingers

should work

UPDATE: defining both in scope

scope :msr, includes(fathers: :kids).order('kids.fingers DESC')

Upvotes: 1

Related Questions