Q:

Rails 4 error: Undefined method 'sort'

I have a model Thing which has a method popularity_rating. Each Thing has_many UpVotes and DownVotes, and these are used to calculate the rating. I'm trying to list all Things on my home page in decreasing order of Rating, but I'm getting this error:
NoMethodError in HomePageController#home
undefined method `sort' for #<Class:0x007f98edd7d330>

Controllers/home_page_controller.rb:
class HomePageController < ApplicationController
   def home
     @topten = Thing.sort { |a, b| a.popularity_rating.to_f <=> b.popularity_rating.to_f }
   end
end

Models/thing.rb
# ...
has_many :up_votes, as: :voteable
has_many :down_votes, as: :voteable

def popularity_rating
  100 * ( (self.up_votes.count.to_f)  / ( (self.up_votes.count.to_f) + ( self.down_votes.count.to_f ) ) )
end

Models/up_votes.rb
belongs_to :voteable, polymorphic: true

A:

There is no method sort directly on a model, especially not as you have it there. That's how you'd deal with a Ruby array, and even then sort_by { |t| t.rating.to_f } is preferable.
What you want is:
@topten = Thing.order(rating: :desc).limit(10)

This presumes rating is a column in your database and not a method like you've described there. If you need to compute this value, do that in your model and save it to the database each time. Loading everything, sorting, and discarding all but ten records is extremely slow.

