From ea8cb4b0778f8119dafe48633f7c21a3f5e5f52d Mon Sep 17 00:00:00 2001 From: Petko Bordjukov Date: Thu, 13 Oct 2016 06:10:56 +0300 Subject: [PATCH] Optimise conflicts calculation --- app/models/conflicts.rb | 15 ++++++--------- app/models/summary.rb | 18 ++++++++++++++++-- .../20161013023851_add_conflicts_view.rb | 19 +++++++++++++++++++ 3 files changed, 41 insertions(+), 11 deletions(-) create mode 100644 db/migrate/20161013023851_add_conflicts_view.rb diff --git a/app/models/conflicts.rb b/app/models/conflicts.rb index 0af18f8..aafbf5c 100644 --- a/app/models/conflicts.rb +++ b/app/models/conflicts.rb @@ -1,12 +1,9 @@ -class Conflicts - include ActiveModel::Model +class Conflicts < ApplicationRecord + def self.most + order(conflicts: :desc).try(:first) + end - attr_accessor :left, :right - - def conflicts - TalkPreference.joins('INNER JOIN "selected_talks" AS "left" - ON "left"."talk_preference_id" = "talk_preferences"."unique_id" - INNER JOIN "selected_talks" AS "right" - ON "right"."talk_preference_id" = "talk_preferences"."unique_id"').where(left: {talk_id: @left}, right: {talk_id: @right}).count + def self.least + order(conflicts: :asc).try(:first) end end diff --git a/app/models/summary.rb b/app/models/summary.rb index 36b6fe1..65fc8b3 100644 --- a/app/models/summary.rb +++ b/app/models/summary.rb @@ -10,14 +10,28 @@ class Summary end def most_conflicts - ConflictsForTalk.where(talk_id: talk_ids).most.conflicts + Conflicts.where(left: talk_ids, right: talk_ids).most.conflicts end def least_conflicts - ConflictsForTalk.where(talk_id: talk_ids).least.conflicts + if least_conflicts_for_single_talk == 0 + 0 + else + least_conflicts_between_two_talks + end end def ranking @ranking ||= Ranking.new(talk_ids: talk_ids).ranking end + + private + + def least_conflicts_for_single_talk + ConflictsForTalk.where(talk_id: talk_ids).least.conflicts + end + + def least_conflicts_between_two_talks + Conflicts.where(left: talk_ids, right: talk_ids).least.conflicts + end end diff --git a/db/migrate/20161013023851_add_conflicts_view.rb b/db/migrate/20161013023851_add_conflicts_view.rb new file mode 100644 index 0000000..0f521ab --- /dev/null +++ b/db/migrate/20161013023851_add_conflicts_view.rb @@ -0,0 +1,19 @@ +CONFLICTS_VIEW_SQL = <