From 32107a9a72c08ca21f3cc9eb4f4beb13b9224279 Mon Sep 17 00:00:00 2001 From: Daniel Waterworth Date: Wed, 30 Oct 2019 14:45:34 +0000 Subject: [PATCH] FIX: Correct slug validation We were allowing new categories to use slugs like "2342-category". --- app/models/category.rb | 9 +++++---- spec/requests/list_controller_spec.rb | 12 +++++++++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/app/models/category.rb b/app/models/category.rb index 8c216ac6878..ecec90e437c 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -294,10 +294,11 @@ class Category < ActiveRecord::Base self.slug = Slug.for(name, '') self.slug = '' if duplicate_slug? end - # only allow to use category itself id. new_record doesn't have a id. - unless new_record? - match_id = /^(\d+)-category/.match(self.slug) - errors.add(:slug, :invalid) if match_id && match_id[1] && match_id[1] != self.id.to_s + + # only allow to use category itself id. + match_id = /^(\d+)-/.match(self.slug) + if match_id.present? + errors.add(:slug, :invalid) if new_record? || (match_id[1] != self.id.to_s) end end diff --git a/spec/requests/list_controller_spec.rb b/spec/requests/list_controller_spec.rb index 9727a06d4cb..279acbff67c 100644 --- a/spec/requests/list_controller_spec.rb +++ b/spec/requests/list_controller_spec.rb @@ -400,7 +400,17 @@ RSpec.describe ListController do context 'another category exists with a number at the beginning of its name' do # One category has another category's id at the beginning of its name - let!(:other_category) { Fabricate(:category_with_definition, name: "#{category.id} name") } + let!(:other_category) { + # Our validations don't allow this to happen now, but did historically + Fabricate(:category_with_definition, name: "#{category.id} name", slug: '-').tap { |c| + DB.exec <<~SQL + UPDATE categories + SET slug = '#{category.id}-name' + WHERE id = #{c.id} + SQL + c.reload + } + } it 'uses the correct category' do get "/c/#{other_category.slug}/l/latest.json"