如何使用 ActiveRecord 2.3 按多态子属性的平均值进行排序?

发布于 2024-09-26 13:41:25 字数 276 浏览 8 评论 0原文

我有这样的架构:

class Comment
  has_many :ratings, :as => :target
end

class Rating
  belongs_to :target, :polymorphic => true
end

我想编写一个命名范围,它将按评论的平均评分对评论进行排序,而无需获取整个评论列表,然后获取其所有评分。

我想我需要使用 :include 和 :group,但是我也使用 :order 吗?谢谢。

I have this schema:

class Comment
  has_many :ratings, :as => :target
end

class Rating
  belongs_to :target, :polymorphic => true
end

I want to write 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清风夜微凉 2024-10-03 13:41:26

这是我的做法:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文