[英]Rails 4 error: Undefined method 'sort'
I have a model Thing
which has a method popularity_rating
. 我有一个Thing
模型,它的方法为popularity_rating
。 Each Thing has_many UpVotes and DownVotes, and these are used to calculate the rating. 每个事物都有多个UpVotes和DownVotes,这些用于计算评分。 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: 控制器/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 型号/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 型号/up_votes.rb
belongs_to :voteable, polymorphic: true
There is no method sort
directly on a model, especially not as you have it there. 没有直接在模型上进行方法sort
方法,特别是没有在那里进行sort
方法。 That's how you'd deal with a Ruby array, and even then sort_by { |t| t.rating.to_f }
这就是处理Ruby数组的方法,甚至是sort_by { |t| t.rating.to_f }
sort_by { |t| t.rating.to_f }
is preferable. sort_by { |t| t.rating.to_f }
是可取的。
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. 该假定rating
是数据库中的一列,而不是您在此处描述的方法。 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. 加载的一切 ,整理,并丢弃所有,但十个记录是极其缓慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.