How can I sort by the average of a polymorphic child's attribute with ActiveRecord 2.3?
I have this schema:
class Comment
has_many :ratings, :as => :target
end
class Rating
belongs_to :target, :polymorphic => true
end
I want to wr开发者_Python百科ite a named scope that will sort comments by their average rating, without fetching the whole list of comments and then fetching all their ratings.
I think I need to use :include and :group, but do I also use :order? Thanks.
Here's what I went with:
module Ratable
def self.included base
base.has_many :ratings, :as => :target, :dependent => :destroy
base.named_scope :rated, :joins => :ratings, :group => 'target_id', :select => "#{base.table_name}.*, avg(ratings.opinion) as 'average_rating'", :order => 'average_rating desc'
end
end
精彩评论