2015-07-20 16:01:08 +00:00
module JamRuby
class Review < ActiveRecord :: Base
attr_accessible :target , :rating , :description , :user
belongs_to :target , polymorphic : true
belongs_to :user , foreign_key : 'user_id' , class_name : " JamRuby::User "
belongs_to :deleted_by_user , foreign_key : 'deleted_by_user_id' , class_name : " JamRuby::User "
validates :rating , presence : true , numericality : { only_integer : true , minimum : 1 , maximum : 5 }
2015-07-20 16:29:19 +00:00
2015-07-20 16:01:08 +00:00
validates :target , presence : true
validates :user , presence : true
2015-07-20 16:29:19 +00:00
validates :target_id , uniqueness : { scope : :user_id , message : " There is already a review for this User and Target. " }
2015-07-20 21:49:22 +00:00
class << self
2015-07-21 01:33:20 +00:00
def index ( options = { } )
if ( options . key? ( :include_deleted ) )
arel = Review . select ( " * " )
else
arel = Review . where ( " deleted_at IS NULL " )
end
if ( options . key? ( :target_id ) )
arel = arel . where ( " target_id=? " , options [ :target_id ] )
end
if ( options . key? ( :user_id ) )
arel = arel . where ( " user_id=? " , options [ :user_id ] )
end
arel
end
2015-07-21 00:11:52 +00:00
# Create review_summary records by grouping reviews
2015-07-20 21:49:22 +00:00
def reduce ( )
ReviewSummary . transaction do
ReviewSummary . destroy_all
2015-07-21 01:33:20 +00:00
Review . select ( " target_id, target_type AS target_type, AVG(rating) as avg_rating, count(*) as review_count, SUM(CASE WHEN rating>=3.0 THEN 1 ELSE 0 END) AS pos_count " )
. where ( " deleted_at IS NULL " )
. group ( " target_type, target_id " )
. each do | r |
wilson_score = ci_lower_bound ( r . pos_count , r . review_count )
ReviewSummary . create! (
target_id : r . target_id ,
target_type : r . target_type ,
avg_rating : r . avg_rating ,
wilson_score : wilson_score ,
review_count : r . review_count
)
2015-07-20 21:49:22 +00:00
end # each
end # transaction
end # reduce
def ci_lower_bound ( pos , n , confidence = 0 . 95 )
pos = pos . to_f
n = n . to_f
return 0 if n == 0
z = 1 . 96 # Statistics2.pnormaldist(1-(1-confidence)/2)
phat = 1 . 0 * pos / n
( phat + z * z / ( 2 * n ) - z * Math . sqrt ( ( phat * ( 1 - phat ) + z * z / ( 4 * n ) ) / n ) ) / ( 1 + z * z / n )
end
end # self
2015-07-20 16:01:08 +00:00
end
end