From eebc6b8badbdc7a85d499ba521a8a7aaad0b738f Mon Sep 17 00:00:00 2001 From: Rodrigo Souto Date: Thu, 30 Apr 2015 02:38:28 -0300 Subject: [PATCH] tags: migration to fix tags case differences --- db/migrate/20150423203352_fix_tags_case_differences.rb | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+), 0 deletions(-) create mode 100644 db/migrate/20150423203352_fix_tags_case_differences.rb diff --git a/db/migrate/20150423203352_fix_tags_case_differences.rb b/db/migrate/20150423203352_fix_tags_case_differences.rb new file mode 100644 index 0000000..13fe181 --- /dev/null +++ b/db/migrate/20150423203352_fix_tags_case_differences.rb @@ -0,0 +1,19 @@ +class FixTagsCaseDifferences < ActiveRecord::Migration + def up + tags = ActsAsTaggableOn::Tag.joins('LEFT JOIN tags as b on LOWER(tags.name) = b.name').where('b.id is null') + tags.find_each do |tag| + unless ActsAsTaggableOn::Tag.exists?(:name => tag.name.mb_chars.downcase) + ActsAsTaggableOn::Tag.create(:name => tag.name.mb_chars.downcase) + end + end + + execute("UPDATE taggings SET tag_id = new.id FROM taggings AS t INNER JOIN tags AS old ON t.tag_id = old.id INNER JOIN tags AS new ON LOWER(old.name) = new.name WHERE old.id != new.id AND taggings.id = t.id") + + execute("UPDATE tags SET taggings_count = (SELECT COUNT(*) FROM taggings WHERE taggings.tag_id = tags.id)") + execute("DELETE FROM tags WHERE taggings_count = 0") + end + + def down + say 'This migration is irreversible.' + end +end -- libgit2 0.21.2