ksol
ksol

Reputation: 12235

Sort collection according to field in association

I'm having a trouble finding how to do a query with MongoDB/Mongoid here. So I have a model User, that has_many :scores, Score being another model that has a code and a value. The code is unique in the scope of the user. For a given code I want to get the users, sorted by the value of the score.

Basically, what I want to do is something like : User.where('scores.code' => code).order_by('scores.value'), except it cannot be done like this. I tried several things, and I think the answer is related to User.where(:scores.matches => {:code => code}), but this does not return me anything, so I must be missing something here..

Thanks for your time, hope I was clear enough!

Upvotes: 1

Views: 404

Answers (1)

Ren
Ren

Reputation: 678

I think this is probably what you want:

scores = Score.where('code' => code).order_by('value')

If you want to get the user (assuming that Score class has belongs_to :user), then you can do this:

users_that_matches_code = scores.map { |s| s.user }

Upvotes: 1

Related Questions