Optimise conflicts calculation

This commit is contained in:
Petko Bordjukov 2016-10-13 06:10:56 +03:00
parent 1a80614471
commit ea8cb4b077
3 changed files with 41 additions and 11 deletions

View File

@ -1,12 +1,9 @@
class Conflicts class Conflicts < ApplicationRecord
include ActiveModel::Model def self.most
order(conflicts: :desc).try(:first)
end
attr_accessor :left, :right def self.least
order(conflicts: :asc).try(:first)
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
end end
end end

View File

@ -10,14 +10,28 @@ class Summary
end end
def most_conflicts def most_conflicts
ConflictsForTalk.where(talk_id: talk_ids).most.conflicts Conflicts.where(left: talk_ids, right: talk_ids).most.conflicts
end end
def least_conflicts 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 end
def ranking def ranking
@ranking ||= Ranking.new(talk_ids: talk_ids).ranking @ranking ||= Ranking.new(talk_ids: talk_ids).ranking
end 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 end

View File

@ -0,0 +1,19 @@
CONFLICTS_VIEW_SQL = <<EOS
CREATE VIEW "conflicts" AS
SELECT "left"."talk_id" AS left, "right"."talk_id" AS right, COUNT(*) AS "conflicts"
FROM "selected_talks" AS "left"
INNER JOIN "selected_talks" AS "right"
ON "left"."talk_preference_id" = "right"."talk_preference_id"
WHERE "left"."talk_id" != "right"."talk_id"
GROUP BY "left"."talk_id", "right"."talk_id";
EOS
class AddConflictsView < ActiveRecord::Migration[5.0]
def up
execute CONFLICTS_VIEW_SQL
end
def down
execute 'DROP VIEW "conflicts"'
end
end