1

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!

ksol
  • 11,835
  • 5
  • 37
  • 64
  • FYI, I remodeled to achieve what I want, but am still interested in the answer. – ksol Feb 21 '12 at 16:35
  • Hi, I am little confused with your question. You mentioned that code is unique per user. But your example 'User.where('scores.code' => code).order_by('scores.value')' implies that there are many users that share a code. – Ren Feb 21 '12 at 21:30
  • For a given code, a user will have 0 or 1 corresponding score. But other users can (and will) have scores for this level too. That's what I meant by 'unique in the scope of user' – ksol Feb 21 '12 at 21:49

1 Answers1

1

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 }
Ren
  • 678
  • 4
  • 6