2016-02-19 37 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 –

相關問題