0

In my app, I have a Product model which has_many Reviews.

In my controller, I'd just like to order the array of Products by the count of how many reviews there are.

Controller

@search = Product.search_attributes(params[:search])
@products = @search.sort_by_reviews_count

Product model:

def self.sort_by_reviews_count
  self.sort! { |x,y| x.reviews.count <=> y.reviews.count }
end

However, I am getting the following error:

undefined method `sort!' for #<Class:0x007ff019ebf468>

Why is this happening?

4

1 回答 1

2

因为您正在尝试对Product < ActiveRecord::Base班级进行排序。那没有意义。

您也许可以使用 AR 关系对数据库中的关联进行排序,但我不确定如何。

如果您不介意在应用程序中进行排序,您应该可以这样做:

def self.sort_by_reviews_count
  self.all.sort! { |x,y| x.reviews.count <=> y.reviews.count }
end
于 2013-06-02T22:42:56.070 回答