ruby - Rails 4 error: Undefined method 'sort' -
i have model thing
has method popularity_rating
. each thing has_many upvotes , downvotes, , these used calculate rating. i'm trying list things on home page in decreasing order of rating, i'm getting error:
nomethoderror in homepagecontroller#home undefined method `sort' #<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
there no method sort
straight on model, not have there. that's how you'd deal ruby array, , sort_by { |t| t.rating.to_f }
preferable.
what want is:
@topten = thing.order(rating: :desc).limit(10)
this presumes rating
column in database , not method you've described there. if need compute value, in model , save database each time. loading everything, sorting, , discarding 10 records extremely slow.
ruby-on-rails ruby sorting ruby-on-rails-4
No comments:
Post a Comment