views:

79

answers:

3

Look:

class User < ActiveRecord::Base
  has_many :scores, :order => 'score DESC',:autosave =>true,
end

class Score < ActiveRecord::Base
  belongs_to :user  
end

Now, I want to order the users by the maximun score of each one,

The thing is that i need to get a user, two up and two down users

like a top 5 scores

how can I do that????

please is urgent!!

A: 

You can try this:

# get each user max scores, returns an array of hash
user_max_scores = User.all.map do |u|
  max_score = u.scores.first # This is the user max score since you order it DESC
  {:user => u, :score => max_score}
end

# now to get the top 5 scores, the lowest is the highest user, in an array of hash
top_5_scores = user_max_scores.sort_by {|e| e[:score].score}.last(5)

# to use it, for example to get no 1 user object and no 1 score object
top_user  = top_5_scores.last[:user] 
top_score = top_5_scores.last[:score]

Hopefully it helps.

SamChandra
+1  A: 
class User < ActiveRecord::Base
  has_many :scores, :order => 'score DESC',:autosave =>true,

  named_scope :top_score, :joins => :scores, :conditions => "scores.id is not null", :order => "scores.score DESC"
end

You can call it:

@users = User.top_score(:limit => 5)

It should work, but I didn't test it!

klew
A: 

So much thanks!!!!!

The solution with the sort_by work for me. The first one, no tryed, but I like it,

thanks!!! :)

Daniel G. R.