2014-06-20 86 views
1

我使用activerecord_reputation_system寶石率什麼的總數ActiveRecord的信譽系統,我們稱之爲模型X.在應用程序/模型/ x.rb我Ruby on Rails的爲平均評級,評級

has_reputation :rating, source: :user, aggregated_by: :average 

這讓我查看平均評分。

我的問題:如何查看模型X的平均評分和總票數?一種方法是添加到應用程序/模型/ x.rb:

has_reputation :rating, source: :user, aggregated_by: :average 
has_reputation :reviews, source: :user, aggregated_by: :sum 

,並在控制器中有:

value = params[:rating] 
@x = X.find(params[:id]) 
if X.where(id: params[:id]).evaluated_by(:reviews, current_user).blank? 
    @x.add_or_update_evluation(:reviews, 1, current_user) 
end 
@x.add_or_update_evaluation(:rating, value, current_user) 

這是做的最好的方法還是有更好的辦法?

非常感謝。

回答

2

我認爲你可以這樣做:

class Vote < ActiveRecord::Base 
belongs_to :x 
attr_accessible :rate #it can be in range 1..5 

def rating 
    rate 
end 
end  

class X < ActiveRecord::Base 
has_many :votes 

def average_rating 
    unless votes.empty? 
    (self.votes.sum(&:rating)/number_of_votes.to_f).round 
    end 
end 

def number_of_votes 
    self.votes.count 
end 
end 

您也可以使用寶石:https://github.com/muratguzel/letsrate

讓我知道這是一個很好的解決方案。