2016-02-19 38 views
0

伙计!我想根据总评分得分对评论进行排序,其中总评分是每个评论的评分评分属性总和。如何基于Ruby on Rails中一组关联中的特定属性的总和对记录进行排序?

class Rating < ActiveRecord::Base 
    belongs_to :comment, :class_name => 'Comment', :foreign_key => 'comment_id' 

end 

class Comment < ActiveRecord::Base 
    has_many :ratings 
end 

Rating schema 
    create_table "ratings", force: true do |t| 
    t.integer "user_id" 
    t.integer "comment_id" 
    t.integer "score" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

感谢您的帮助!

+0

你正在使用什么RDBMS? –

+0

MySQL,谢谢。 – nebulus

回答

1

您应该能够通过相关记录列的总和这样

Comment.joins(:ratings).group('comments.id').order('sum(ratings.score) desc') 
+0

谢谢!这工作。 – nebulus

1

看看这个答案,通过选择呼叫进行计数。 Order Players on the SUM of their association model。这将是建议的方式。

另一种方法是在评论模型中添加一个方法来将所有评分的分数相加。

def rating_score_sum 
    ratings.sum(:score) 
end 

然后,您可以使用该方法对您的集合进行排序。

Comment.all.sort_by(&:rating_score_sum) 

虽然这会计算每次评论的所有评级的评分总和,并可能随着数据库的增长而成为问题。我会考虑在评论表上保存这笔款项,并在每个新评级上更新它。

干杯!

1

订购您应该能够做到这一点很容易:

Comment.joins(:ratings).select('comments.*, SUM(ratings.score) as rating_score').order('rating_score DESC') 

您也可以尝试使用includes代替joins甚至eager_load,因为它会预加载关联(评级)并改善此查询的性能。

+0

如果您使用的是Postgres,则不需要。你需要一个小组条款。 – MilesStanfield

+0

当然可以。我的回答是基于:您使用的是什么RDBMS? - Arup Rakshit,MySQL,谢谢。 - nebulus –

相关问题