From 485116e29c6f0c7befec5d861c3248a40e4931ef Mon Sep 17 00:00:00 2001 From: Petko Bordjukov Date: Thu, 6 Oct 2016 20:30:28 +0300 Subject: [PATCH] Optimize ratings calculation --- app/controllers/home_controller.rb | 2 +- app/models/ratings.rb | 11 ++--------- app/views/home/_talk.html.erb | 8 -------- app/views/home/ratings.html.erb | 11 ++++++++++- 4 files changed, 13 insertions(+), 19 deletions(-) diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 7d1be76..2d1dbe8 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -5,7 +5,7 @@ class HomeController < ApplicationController def ratings @talks = Talk.ordered_by_rating @ratings = Ratings.new - @votes_count = TalkPreference.count + @votes_count = TalkPreference.this_years.count end def export diff --git a/app/models/ratings.rb b/app/models/ratings.rb index 1ba0a49..920f123 100644 --- a/app/models/ratings.rb +++ b/app/models/ratings.rb @@ -1,16 +1,9 @@ class Ratings - @ratings = Hash.new(0) - def initialize - ratings = TalkPreference.all.pluck(:talks).reduce(Hash.new(0)) do |result, talks| - talks.map(&:to_i).each { |talk| result[talk] += 1 } - result - end.to_h - - @ratings = Hash.new(0).merge!(ratings) + @ratings = {} end def [](id) - @ratings[id] + @ratings[id] ||= SelectedTalk.where(talk_id: id).count end end diff --git a/app/views/home/_talk.html.erb b/app/views/home/_talk.html.erb index 8b90eae..e69de29 100644 --- a/app/views/home/_talk.html.erb +++ b/app/views/home/_talk.html.erb @@ -1,8 +0,0 @@ - - <%= talk.id %> - <%= talk.event_type.name %> - <%= talk.title %> - <%= talk.subtitle %> - <%= @ratings[talk.id] %> - <%= "%.2f%" % Rational(100 * @ratings[talk.id], @votes_count).to_f %> - diff --git a/app/views/home/ratings.html.erb b/app/views/home/ratings.html.erb index d11a174..d57a9b1 100644 --- a/app/views/home/ratings.html.erb +++ b/app/views/home/ratings.html.erb @@ -10,6 +10,15 @@ - <%= render partial: 'talk', collection: @talks %> + <% @talks.each do |talk| %> + + <%= talk.id %> + <%= talk.event_type.name %> + <%= talk.title %> + <%= talk.subtitle %> + <%= @ratings[talk.id] %> + <%= "%.2f%" % Rational(100 * @ratings[talk.id], @votes_count).to_f %> + + <% end %>