How to calculate specific rating count hash in ruby on rails?

twinkle :

So, I have an after_save hook on review model which calls calculate_specific_rating function of product model. The function goes like this:

def calculate_specific_rating
    ratings = reviews.reload.all.pluck(:rating)
    specific_rating = Hash.new(0)
    ratings.each { |rating| specific_rating[rating] += 1 }
    self.specific_rating = specific_rating
    save
  end

Right now, it returns

specific_rating => { 
"2"=> 3, "4"=> 1
}

I want it to return like:

specific_rating => { 
"1"=> 0, "2"=>3, "3"=>0, "4"=>1, "5"=>0
}

Also, is it okay to initialize a new hash everytime a review is saved? I want some alternative. Thanks

Sebastian Palma :

You can create a range from 1 until the maximum value in ratings plus 1 and start iterating through it, yielding an array where the first element is the current one, and the second element is the total of times the current element is present in ratings. After everything the result is converted to a hash:

self.specific_rating = (1..ratings.max + 1).to_h { |e| [e.to_s, ratings.count(e)] }
save

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=368081&siteId=1