【发布时间】:2015-12-18 10:52:20
【问题描述】:
我有一个名为 product 的自定义模型,它有很多评论。
我有一个计算评论的方法
def rating
total = 0
reviews_count = reviews.count
return 0 if reviews_count == 0
reviews.each do |review|
total += review.grade
end
total.to_f/reviews_count
end
我想知道如何使用这种方法订购我的产品。
在 products_controller.rb,如果我使用:
@products = Product.all.order("price")
很简单,它给了我按价格排序的产品列表。但是,如果我使用,例如:
@products = Product.all.sort_by{|p| p.rating}
它给了我一个数组而不是“ActiveRecord::Relation”
我想知道如何使用返回值的自定义方法订购我的产品。
【问题讨论】:
标签: ruby-on-rails ruby sorting