From 79c986dd92d77d4a9f3863ae83d9cb086b6843e2 Mon Sep 17 00:00:00 2001
From: Robin Ward <robin.ward@gmail.com>
Date: Mon, 1 Apr 2013 12:26:51 -0400
Subject: [PATCH] Fix issue with duplicate slugs

---
 app/models/category.rb       | 12 ++++++++++--
 spec/models/category_spec.rb |  6 ++++++
 2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/app/models/category.rb b/app/models/category.rb
index 9a23f10ac70..a77c9c6ee2f 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -17,7 +17,7 @@ class Category < ActiveRecord::Base
   validates :name, presence: true, uniqueness: true, length: { in: 1..50 }
   validate :uncategorized_validator
 
-  before_save :ensure_slug
+  before_validation :ensure_slug
   after_save :invalidate_site_cache
   after_create :create_category_definition
   after_destroy :invalidate_site_cache
@@ -38,7 +38,15 @@ class Category < ActiveRecord::Base
   end
 
   def ensure_slug
-    self.slug = Slug.for(name)
+    if name.present?
+      self.slug = Slug.for(name)
+
+      # If a category with that slug already exists, set the slug to nil so the category can be found
+      # another way.
+      category = Category.where(slug: self.slug)
+      category = category.where("id != ?", id) if id.present?
+      self.slug = '' if category.exists?
+    end
   end
 
   # Categories are cached in the site json, so the caches need to be
diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rb
index b70cb9c9c7a..fbc26929cce 100644
--- a/spec/models/category_spec.rb
+++ b/spec/models/category_spec.rb
@@ -115,6 +115,12 @@ describe Category do
       @category.topic_url.should be_present
     end
 
+    describe "creating a new category with the same slug" do
+      it "should have a blank slug" do
+        Fabricate(:category, name: "Amazing Categóry").slug.should be_blank
+      end
+    end
+
     describe "trying to change the category topic's category" do
       before do
         @new_cat = Fabricate(:category, name: '2nd Category', user: @category.user)