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 }