Working on tag name uniqueness
This commit is contained in:
parent
8af6fab0a4
commit
d825463472
2 changed files with 38 additions and 1 deletions
37
db/migrate/20110406203720_tag_name_uniqueness.rb
Normal file
37
db/migrate/20110406203720_tag_name_uniqueness.rb
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
class TagNameUniqueness < ActiveRecord::Migration
|
||||
def self.downcase_tags
|
||||
execute <<SQL
|
||||
UPDATE tags
|
||||
SET tags.name = LOWER(tags.name)
|
||||
WHERE tags.name != LOWER(tags.name)
|
||||
SQL
|
||||
end
|
||||
def self.consolidate_duplicate_tags
|
||||
duplicate_rows = execute <<SQL
|
||||
SELECT count(tags.name), tags.name FROM tags
|
||||
GROUP BY tags.name
|
||||
HAVING COUNT(*) > 1
|
||||
SQL
|
||||
duplicate_rows.each do |row|
|
||||
name = row.last
|
||||
tag_ids = execute("SELECT tags.id FROM tags WHERE tags.name = '#{name}'").to_a.flatten!
|
||||
id_to_keep = tag_ids.pop
|
||||
execute <<SQL
|
||||
UPDATE taggings
|
||||
SET taggings.tag_id = #{id_to_keep}
|
||||
WHERE taggings.tag_id IN (#{tag_ids.join(',')})
|
||||
SQL
|
||||
execute("DELETE tags WHERE tags.id IN (#{tag_ids.join(',')})")
|
||||
end
|
||||
end
|
||||
|
||||
def self.up
|
||||
downcase_tags
|
||||
consolidate_duplicate_tags
|
||||
add_index :tags, :name, :unique => true
|
||||
end
|
||||
|
||||
def self.down
|
||||
raise ActiveRecord::IrreversibleMigration.new
|
||||
end
|
||||
end
|
||||
|
|
@ -10,7 +10,7 @@
|
|||
#
|
||||
# It's strongly recommended to check this file into your version control system.
|
||||
|
||||
ActiveRecord::Schema.define(:version => 20110405170101) do
|
||||
ActiveRecord::Schema.define(:version => 20110406203720) do
|
||||
|
||||
create_table "aspect_memberships", :force => true do |t|
|
||||
t.integer "aspect_id", :null => false
|
||||
|
|
|
|||
Loading…
Reference in a new issue