Very simple. First, you would add the average_rating
column to your Hotel model with a migration. Then, you would add a callback to your Rating model which updates the value in the Hotel model. Basically, every time a rating is created, destroyed, or updated, you need to update the average rating. It would look something like this:
class Hotel < ActiveRecord::Base
[ code snipped ]
def update_average_rating
@value = 0
self.ratings.each do |rating|
@value = @value + rating.value
end
@total = self.ratings.size
update_attributes(average_rating: @value.to_f / @total.to_f)
end
end
class Rating
belongs_to :hotel
after_create :update_hotel_rating
def update_hotel_rating
hotel.update_average_rating
end
end
Now you can easily sort by rating. I'm leaving some details out but I think you can get the general idea here.