开发者

How can I sort by the average of a polymorphic child's attribute with ActiveRecord 2.3?

开发者 https://www.devze.com 2023-01-19 01:16 出处:网络
I have this schema: class Comment has_many :ratings, :as => :target end class Rating belongs_to :target, :polymorphic => true

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
0

精彩评论

暂无评论...
验证码 换一张
取 消