From 7900c7bd2f38995d27cbe0432939459504c145b4 Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Mon, 26 May 2014 15:33:51 -0400 Subject: [PATCH] Allow multiple subcategories with the same name --- app/models/category.rb | 4 ++-- .../20140526185749_change_category_uniquness_contstraint.rb | 6 ++++++ spec/models/category_spec.rb | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) create mode 100644 db/migrate/20140526185749_change_category_uniquness_contstraint.rb diff --git a/app/models/category.rb b/app/models/category.rb index 2250093cf..7c7b13a05 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -23,7 +23,7 @@ class Category < ActiveRecord::Base has_many :groups, through: :category_groups validates :user_id, presence: true - validates :name, presence: true, uniqueness: true, length: { in: 1..50 } + validates :name, presence: true, uniqueness: { scope: :parent_category_id }, length: { in: 1..50 } validate :parent_category_validator before_validation :ensure_slug @@ -161,7 +161,7 @@ SQL t = Topic.new(title: I18n.t("category.topic_prefix", category: name), user: user, pinned_at: Time.now, category_id: id) t.skip_callbacks = true t.auto_close_hours = nil - t.save! + t.save!(validate: false) update_column(:topic_id, t.id) t.posts.create(raw: post_template, user: user) end diff --git a/db/migrate/20140526185749_change_category_uniquness_contstraint.rb b/db/migrate/20140526185749_change_category_uniquness_contstraint.rb new file mode 100644 index 000000000..65788268c --- /dev/null +++ b/db/migrate/20140526185749_change_category_uniquness_contstraint.rb @@ -0,0 +1,6 @@ +class ChangeCategoryUniqunessContstraint < ActiveRecord::Migration + def change + remove_index :categories, name: 'index_categories_on_name' + add_index :categories, [:parent_category_id, :name], unique: true + end +end diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rb index cb69dc655..29aabc0bc 100644 --- a/spec/models/category_spec.rb +++ b/spec/models/category_spec.rb @@ -9,7 +9,7 @@ describe Category do it 'validates uniqueness of name' do Fabricate(:category) - should validate_uniqueness_of(:name) + should validate_uniqueness_of(:name).scoped_to(:parent_category_id) end it { should belong_to :topic }