ruby on rails - How to sort by results of a method -
i have method on user.rb model in rails app returns reputation score based on user's various contributions 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 index action of imaginary artists controller, retrieve artists, , retrieve filtered 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 location, user model calls scope method
scope :artists_by_province, lambda {|province| joins(:contact). where( contacts: {province_id: province}, users: {onionpealer: true}) } what i'd do, however, is, in both cases (whether filtering location or retrieving users) sort retrieval of artists results of total_votes method, artists highest number of points appear @ top.
can suggest how might that. thank in advance.
if not pay attention on wrong query architecture, sorting can done ruby array#sort_by
@artistsbyprovince = user.artists_by_province(province).sort_by{ |u| -u.total_votes }
Comments
Post a Comment