Fix issue with duplicate slugs

This commit is contained in:
Robin Ward 2013-04-01 12:26:51 -04:00
parent e4d190d856
commit 79c986dd92
2 changed files with 16 additions and 2 deletions

View File

@ -17,7 +17,7 @@ class Category < ActiveRecord::Base
validates :name, presence: true, uniqueness: true, length: { in: 1..50 } validates :name, presence: true, uniqueness: true, length: { in: 1..50 }
validate :uncategorized_validator validate :uncategorized_validator
before_save :ensure_slug before_validation :ensure_slug
after_save :invalidate_site_cache after_save :invalidate_site_cache
after_create :create_category_definition after_create :create_category_definition
after_destroy :invalidate_site_cache after_destroy :invalidate_site_cache
@ -38,7 +38,15 @@ class Category < ActiveRecord::Base
end end
def ensure_slug 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 end
# Categories are cached in the site json, so the caches need to be # Categories are cached in the site json, so the caches need to be

View File

@ -115,6 +115,12 @@ describe Category do
@category.topic_url.should be_present @category.topic_url.should be_present
end 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 describe "trying to change the category topic's category" do
before do before do
@new_cat = Fabricate(:category, name: '2nd Category', user: @category.user) @new_cat = Fabricate(:category, name: '2nd Category', user: @category.user)