From e40e9351f6b991d181ebae059eff66c3304661e0 Mon Sep 17 00:00:00 2001
From: Neil Lalonde <neillalonde@gmail.com>
Date: Mon, 11 Aug 2014 16:55:26 -0400
Subject: [PATCH] FIX: don't allow same category name with different case

---
 app/models/category.rb       | 5 ++++-
 app/models/topic.rb          | 2 +-
 spec/models/category_spec.rb | 7 +++++++
 3 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/app/models/category.rb b/app/models/category.rb
index e09e40315..c03972bfa 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -23,7 +23,10 @@ class Category < ActiveRecord::Base
   has_many :groups, through: :category_groups
 
   validates :user_id, presence: true
-  validates :name, presence: true, uniqueness: { scope: :parent_category_id }, length: { in: 1..50 }
+  validates :name, if: Proc.new { |c| c.new_record? || c.name_changed? },
+                   presence: true,
+                   uniqueness: { scope: :parent_category_id, case_sensitive: false },
+                   length: { in: 1..50 }
   validate :parent_category_validator
 
   before_validation :ensure_slug
diff --git a/app/models/topic.rb b/app/models/topic.rb
index 8acf4f971..3d0ca4bb5 100644
--- a/app/models/topic.rb
+++ b/app/models/topic.rb
@@ -48,7 +48,7 @@ class Topic < ActiveRecord::Base
   rate_limit :limit_topics_per_day
   rate_limit :limit_private_messages_per_day
 
-  validates :title, :if => Proc.new { |t| t.title_changed? },
+  validates :title, :if => Proc.new { |t| t.new_record? || t.title_changed? },
                     :presence => true,
                     :topic_title_length => true,
                     :quality_title => { :unless => :private_message? },
diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rb
index c14d5982d..988505fe4 100644
--- a/spec/models/category_spec.rb
+++ b/spec/models/category_spec.rb
@@ -12,6 +12,13 @@ describe Category do
     should validate_uniqueness_of(:name).scoped_to(:parent_category_id)
   end
 
+  it 'validates uniqueness in case insensitive way' do
+    Fabricate(:category, name: "Cats")
+    c = Fabricate.build(:category, name: "cats")
+    c.should_not be_valid
+    c.errors[:name].should be_present
+  end
+
   it { should belong_to :topic }
   it { should belong_to :user }