Reputation: 42049
I have a method on my User.rb model in my Rails app that returns a reputation score based on a user's various contributions to the site.
def total_votes
answerkarma = AnswerVote.joins(:answer).where(answers: {user_id: self.id}).sum('value')
contributionkarma = Contribution.where(user_id: self.id).sum('value')
answerkarma + contributionkarma
end
In the index action of my imaginary artists controller, sometimes I retrieve all artists, and sometimes I retrieve only those filtered by location
def index
if params[:province_id]
province = params[:province_id]
province = province.to_i
@artistsbyprovince = User.artists_by_province(province)
else
@artists = User.where(:onionpealer => true)
end
end
If I'm filtering by location, the User model calls this scope method
scope :artists_by_province, lambda {|province|
joins(:contact).
where( contacts: {province_id: province},
users: {onionpealer: true})
}
What I'd like to do, however, is, in both cases (whether filtering by location or retrieving all users) is to sort the retrieval of the artists by the results of total_votes method, so that artists with the highest number of points appear at the top.
Can you suggest how I might do that. Thank you in advance.
Upvotes: 1
Views: 47
Reputation: 10038
If do not pay attention on wrong query architecture, sorting can be done by ruby array#sort_by
@artistsbyprovince = User.artists_by_province(province).sort_by{ |u| -u.total_votes }
Upvotes: 1