From 1527aeeef6171dd3e2cab27f59e41aa018eb07c3 Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Mon, 23 Jun 2014 16:14:51 -0400 Subject: [PATCH] FIX: The constraint on parent categories wasn't working properly. --- .../20140623195618_fix_categories_constraint.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 db/migrate/20140623195618_fix_categories_constraint.rb diff --git a/db/migrate/20140623195618_fix_categories_constraint.rb b/db/migrate/20140623195618_fix_categories_constraint.rb new file mode 100644 index 00000000000..5c6daa0cc56 --- /dev/null +++ b/db/migrate/20140623195618_fix_categories_constraint.rb @@ -0,0 +1,11 @@ +class FixCategoriesConstraint < ActiveRecord::Migration + def change + remove_index :categories, name: 'index_categories_on_parent_category_id_and_name' + + # Remove any previous duplicates + execute "DELETE FROM categories WHERE id IN (SELECT id FROM (SELECT id, row_number() over (partition BY parent_category_id, name ORDER BY id) AS rnum FROM categories) t WHERE t.rnum > 1)" + + # Create a proper index for two categories not to have the same parent + execute "CREATE UNIQUE INDEX unique_index_categories_on_name ON categories (COALESCE(parent_category_id, -1), name)" + end +end