From e3727eb6b27a96c769cdafa8e06bb5eef5f395b4 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 25 Mar 2021 19:17:34 -0300 Subject: [PATCH] =?UTF-8?q?no=20permitir=20art=C3=ADculos=20duplicados?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/post.rb | 12 ++++++++++++ test/models/post_test.rb | 17 +++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/app/models/post.rb b/app/models/post.rb index 3b25c1f..cb637f9 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -267,6 +267,18 @@ class Post return false if validate && !valid? # Salir si tenemos que cambiar el nombre del archivo y no pudimos return false if !new? && path.changed? && !update_path! + + # Si el archivo va a estar duplicado, agregar un nĂºmero al slug + if new? && written? + original_slug = slug.value + count = 1 + + while written? + count += 1 + slug.value = "#{original_slug}-#{count}" + end + end + return false unless save_attributes! return false unless write diff --git a/test/models/post_test.rb b/test/models/post_test.rb index ab7dd51..f98d7af 100644 --- a/test/models/post_test.rb +++ b/test/models/post_test.rb @@ -181,4 +181,21 @@ class PostTest < ActiveSupport::TestCase assert_equal title, post.content.value assert post.save end + + test 'no se pueden repetir los nombres' do + title = SecureRandom.hex + post = @site.posts.build(title: title, + description: title, + content: title) + + slug = post.slug.value + + assert post.save + + another_post = @site.posts.build(title: title, description: title, content: title) + + assert_equal slug, another_post.slug.value + assert another_post.save + assert_not_equal slug, another_post.slug.value + end end