Assuming you have a has_many and belongs_to relationship between the two models, you can try using the (very convenient) MySQL GROUP BY clause, which is supported in Rails:
@hall_of_fame = Business.find(
:all,
:joins => :ratings,
:group => 'business_id',
:order => 'AVG(ratings.rating) DESC',
:limit => 10
)
If you want to add an average rating, you can include it in the: select parameter:
@hall_of_fame = Business.find(
:all,
:select => 'businesses.name, AVG(ratings.rating)'
:joins => :ratings,
:group => 'business_id',
:order => 'AVG(ratings.rating) DESC',
:limit => 10
)
Naturally, if there are no conflicting column names between the tables, you can safely remove the leading "companies". and ratings. from the parameters: select and: order.
You might want to create a method with this code in your model instead of having it in the controller, but that is up to you.
source
share