tabletop-companion/app/models/stat.rb

40 lines
944 B
Ruby
Raw Normal View History

2024-06-07 14:38:10 +00:00
# frozen_string_literal: true
class Stat < ApplicationRecord
belongs_to :character_sheet_section
validates :name, presence: true,
length: { maximum: 100 },
uniqueness: { scope: :character_sheet_section_id }
validates :slug, presence: true,
length: { maximum: 100 },
uniqueness: true
validates :value, presence: true,
numericality: true
before_validation :set_slug
private
def set_slug
return if slug.present? || name.blank?
slug = if character_sheet_section.parent_section.present?
[
character_sheet_section.parent_section.name.parameterize,
name.parameterize,
].join("-")
else
slug = name.parameterize
end
suffix = 2
while Stat.exists?(slug:)
slug = "#{slug}-#{suffix}"
suffix += 1
end
self.slug = slug
end
end