diff --git a/app/models/communication/website/author.rb b/app/models/communication/website/author.rb index a81414d3d43dd521f43c9f78d1275aa91afed90e..b60581dae8ba540fcb9487d1aa70b89bb795feb2 100644 --- a/app/models/communication/website/author.rb +++ b/app/models/communication/website/author.rb @@ -39,6 +39,8 @@ class Communication::Website::Author < ApplicationRecord class_name: 'Communication::Website::Post', dependent: :nullify + validates :slug, uniqueness: { scope: :communication_website_id } + scope :ordered, -> { order(:last_name, :first_name) } def to_s diff --git a/app/models/communication/website/category.rb b/app/models/communication/website/category.rb index 5d662a5c3ed5e42ae298a44c315a541a4422e75e..3ae309ba9063d4255ac17e20342d5fb176a2de5c 100644 --- a/app/models/communication/website/category.rb +++ b/app/models/communication/website/category.rb @@ -57,8 +57,8 @@ class Communication::Website::Category < ApplicationRecord foreign_key: 'communication_website_category_id', association_foreign_key: 'communication_website_post_id' - validates :name, presence: true + validates :slug, uniqueness: { scope: :communication_website_id } scope :ordered, -> { order(:position) } diff --git a/app/models/communication/website/page.rb b/app/models/communication/website/page.rb index 5e7b1f45b56247773cfd420db7338f51bf9a7459..2fd61295749cf40dff6242d1422752969172588c 100644 --- a/app/models/communication/website/page.rb +++ b/app/models/communication/website/page.rb @@ -63,8 +63,9 @@ class Communication::Website::Page < ApplicationRecord dependent: :nullify validates :title, presence: true + validates :slug, uniqueness: { scope: :communication_website_id } - before_validation :make_path + before_validation :regenerate_slug, :make_path after_save :update_children_paths if :saved_change_to_path? scope :ordered, -> { order(:position) } @@ -92,6 +93,15 @@ class Communication::Website::Page < ApplicationRecord protected + def regenerate_slug + current_slug = self.slug + n = 0 + while self.class.unscoped.where(communication_website_id: communication_website_id, slug: self.slug).where.not(id: id).exists? + n += 1 + self.slug = [current_slug, n].join('-') + end + end + def make_path self.path = "#{parent&.path}/#{slug}".gsub('//', '/') end diff --git a/app/models/communication/website/post.rb b/app/models/communication/website/post.rb index 51bbcec9b443d3d09c5be483adb9ddd3f48e2088..b689d7c9c56319ca6668973d11007f6db973ef03 100644 --- a/app/models/communication/website/post.rb +++ b/app/models/communication/website/post.rb @@ -53,6 +53,7 @@ class Communication::Website::Post < ApplicationRecord scope :recent, -> { order(published_at: :desc).limit(5) } validates :title, presence: true + validates :slug, uniqueness: { scope: :communication_website_id } def github_path_generated "_posts/#{published_at.year}/#{published_at.strftime "%Y-%m-%d"}-#{slug}.html"