Zephyr4434
Zephyr4434

Reputation: 796

Rails - how to sort by associated attribute

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?

Upvotes: 0

Views: 245

Answers (1)

Niels B.
Niels B.

Reputation: 6310

Because you are trying to sort your Product < ActiveRecord::Base class. That doesn't make sense.

You might be able to sort your associations at the database using an AR relation, but I'm not sure how.

If you don't mind doing the sorting in the application, you should be able to do this:

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

Upvotes: 2

Related Questions