Reputation: 9256
I have the following ActiveRecords
class Product < ActiveRecord::Base
has_many :reviews
end
class Review < ActiveRecord::Base
belongs_to :product
end
Each review object contains a field named 'rating'
I wish to get a list of all products whose average rating is larger than a specific bound.
I don't understand how to use the find command to do this.
Does find let us do things like that?
Upvotes: 2
Views: 254
Reputation: 499
I'd use SQL when queries start asking for things like conditions on aggregated values as this one does. There are various ways of achieving the result you want - this feels most straightforward to me:
bound = 3
products = Product.where('id in
(
select product_id
from reviews
group by product_id
having avg(rating) > ?)', bound)
Upvotes: 1
Reputation: 6138
-Yes, it can do it. Somthing like this should do the trick ...
Product.find(:all, :include => 'reviews', :conditions => ['review.rating > ?', min_rating])
Edit - Just reread your question. You want to use the average rating. I'd resort to SQL to do this, or if it is a common operation, calculate the average rating and store it in the product every time a rating is saved.
Upvotes: 1