From 9428a47604d544d2b523df812b4db970683546a5 Mon Sep 17 00:00:00 2001 From: xilefff <42689203+xilefff@users.noreply.github.com> Date: Tue, 20 Nov 2018 04:16:30 +0100 Subject: [PATCH 1/2] Create unique index migration Adds concurrently unique index between friendable_id and friend_id to prevent duplicate friendships. --- db/migrate/4_add_unique_index_to_friendships.rb | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 db/migrate/4_add_unique_index_to_friendships.rb diff --git a/db/migrate/4_add_unique_index_to_friendships.rb b/db/migrate/4_add_unique_index_to_friendships.rb new file mode 100644 index 0000000..d40c85d --- /dev/null +++ b/db/migrate/4_add_unique_index_to_friendships.rb @@ -0,0 +1,17 @@ +if ActiveRecord.gem_version >= Gem::Version.new('5.0') + class AddUniqueIndexToFriendships < ActiveRecord::Migration[4.2]; end +else + class AddUniqueIndexToFriendships < ActiveRecord::Migration; end +end + +AddUniqueIndexToFriendships.class_eval do + disable_ddl_transaction! + + def self.up + add_index :friendships, [:friendable_id, :friend_id], unique: true, algorithm: :concurrently + end + + def self.down + remove_index :friendships, [:friendable_id, :friend_id] + end +end From 980d1eddcdaf2fb5a82f172f24f8d4b22d95d9fd Mon Sep 17 00:00:00 2001 From: xilefff <42689203+xilefff@users.noreply.github.com> Date: Tue, 20 Nov 2018 14:21:30 +0100 Subject: [PATCH 2/2] Check if unique index already exists Add the unique index unless it already exists between friendable_id and friend_id. --- db/migrate/4_add_unique_index_to_friendships.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/migrate/4_add_unique_index_to_friendships.rb b/db/migrate/4_add_unique_index_to_friendships.rb index d40c85d..7341340 100644 --- a/db/migrate/4_add_unique_index_to_friendships.rb +++ b/db/migrate/4_add_unique_index_to_friendships.rb @@ -8,7 +8,7 @@ class AddUniqueIndexToFriendships < ActiveRecord::Migration; end disable_ddl_transaction! def self.up - add_index :friendships, [:friendable_id, :friend_id], unique: true, algorithm: :concurrently + add_index :friendships, [:friendable_id, :friend_id], unique: true, algorithm: :concurrently unless index_exists? (:friendable_id, :friend_id) end def self.down