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
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论