Optimize ratings calculation

This commit is contained in:
Petko Bordjukov 2016-10-06 20:30:28 +03:00
parent 52cd3716c1
commit 485116e29c
4 changed files with 13 additions and 19 deletions

View File

@ -5,7 +5,7 @@ class HomeController < ApplicationController
def ratings def ratings
@talks = Talk.ordered_by_rating @talks = Talk.ordered_by_rating
@ratings = Ratings.new @ratings = Ratings.new
@votes_count = TalkPreference.count @votes_count = TalkPreference.this_years.count
end end
def export def export

View File

@ -1,16 +1,9 @@
class Ratings class Ratings
@ratings = Hash.new(0)
def initialize def initialize
ratings = TalkPreference.all.pluck(:talks).reduce(Hash.new(0)) do |result, talks| @ratings = {}
talks.map(&:to_i).each { |talk| result[talk] += 1 }
result
end.to_h
@ratings = Hash.new(0).merge!(ratings)
end end
def [](id) def [](id)
@ratings[id] @ratings[id] ||= SelectedTalk.where(talk_id: id).count
end end
end end

View File

@ -1,8 +0,0 @@
<tr>
<td><%= talk.id %></td>
<td><%= talk.event_type.name %></td>
<td><%= talk.title %></td>
<td><%= talk.subtitle %></td>
<td><%= @ratings[talk.id] %></td>
<td><%= "%.2f%" % Rational(100 * @ratings[talk.id], @votes_count).to_f %></td>
</tr>

View File

@ -10,6 +10,15 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<%= render partial: 'talk', collection: @talks %> <% @talks.each do |talk| %>
<tr>
<td><%= talk.id %></td>
<td><%= talk.event_type.name %></td>
<td><%= talk.title %></td>
<td><%= talk.subtitle %></td>
<td><%= @ratings[talk.id] %></td>
<td><%= "%.2f%" % Rational(100 * @ratings[talk.id], @votes_count).to_f %></td>
</tr>
<% end %>
</tbody> </tbody>
</table> </table>