Topic Ratings Plugin

Indeed. I had to add a ‘rating_weight’ property to accommodate deleted posts with ratings (and perhaps to use in the future for weighting ratings differently according to poster, or other metadata such as likes). This subsequently changed the calculation of the topic average from this:

@topic_posts = Post.where(topic_id: post.topic_id)
@all_ratings = PostCustomField.where(post_id: @topic_posts.map(&:id), name: "rating").pluck('value').map(&:to_i)
average = @all_ratings.inject(:+).to_f / @all_ratings.length

to this:

@topic_posts = Post.with_deleted.where(topic_id: post.topic_id)
@ratings = []
@topic_posts.each do |post|
  weight = post.custom_fields["rating_weight"]
  if weight.blank? || weight.to_i > 0
    rating = post.custom_fields["rating"].to_i
    @ratings.push(rating)
  end
end
average = @ratings.inject(:+).to_f / @ratings.length

The rating_weight of deleted posts is set to 0. This logic (I think) accommodates rating weight by only counting ratings if the weight is greater than 0 or is blank (to support posts with ratings posted prior to this change). However, the problem is that it also counts posts without a rating at all… So I’ve changed it to:

@topic_posts = Post.with_deleted.where(topic_id: post.topic_id)
@ratings = []
@topic_posts.each do |post|
  weight = post.custom_fields["rating_weight"]
  if post.custom_fields["rating"] && (weight.blank? || weight.to_i > 0)
   rating = post.custom_fields["rating"].to_i
   @ratings.push(rating)
  end
end
average = @ratings.inject(:+).to_f / @ratings.length 

This also checks if the post has a rating before counting it. A silly mistake on my part really. The problem is that I’m always working on this either early in the morning before work or late at night when the brain is softer…

I hope that fixes it.

2 Likes