Generate table slug and UUID

This commit is contained in:
Trevor Vallender 2024-05-28 20:40:51 +01:00
parent c6072a4cb7
commit 26f42fc232
7 changed files with 42 additions and 14 deletions

View File

@ -16,7 +16,6 @@ class TablesController < ApplicationController
def create
@table = Current.user.tables.new(table_params)
@table.slug = helpers.generate_slug_for(model: Table, string: @table.name)
if @table.save
redirect_to @table, notice: t(".success", name: @table.name)
else

View File

@ -1,8 +1,4 @@
# frozen_string_literal: true
module ApplicationHelper
def generate_slug_for(model:, string:)
# TODO: Need to ensure this is unique for that model
string.parameterize
end
end

View File

@ -10,4 +10,18 @@ class Table < ApplicationRecord
validates :slug, presence: true,
length: { maximum: 100 },
uniqueness: true
validates :uuid, presence: true
before_validation :generate_uuid, if: :new_record?
before_validation :generate_slug
def generate_uuid
self.uuid = SecureRandom.uuid
end
def generate_slug
return if slug.present?
self.slug = "#{name.parameterize}-#{uuid}"
end
end

View File

@ -0,0 +1,7 @@
# frozen_string_literal: true
class AddUuidToTables < ActiveRecord::Migration[7.1]
def change
add_column :tables, :uuid, :uuid, null: false
end
end

3
db/schema.rb generated
View File

@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.1].define(version: 2024_05_28_103921) do
ActiveRecord::Schema[7.1].define(version: 2024_05_28_192517) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
@ -42,6 +42,7 @@ ActiveRecord::Schema[7.1].define(version: 2024_05_28_103921) do
t.bigint "game_system_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.uuid "uuid", null: false
t.index ["game_system_id"], name: "index_tables_on_game_system_id"
t.index ["owner_id"], name: "index_tables_on_owner_id"
t.index ["slug"], name: "index_tables_on_slug", unique: true

View File

@ -1,11 +1,14 @@
table:
name: My Table
slug: my-table
DEFAULTS: &DEFAULTS
owner: trevor
uuid: <%= SecureRandom.uuid %>
slug: $LABEL
table:
<<: *DEFAULTS
name: My Table
game_system: troika
table_two:
my_table_two:
<<: *DEFAULTS
name: My Other Table
slug: my-other-table
owner: trevor
game_system: troika

View File

@ -7,8 +7,8 @@ class TableTest < ActiveSupport::TestCase
assert_must_exist(tables(:table), "name")
end
test "slug must exist" do
assert_must_exist(tables(:table), "slug")
test "uuid must exist" do
assert_must_exist(tables(:table), "uuid")
end
test "slug must be unique" do
@ -17,4 +17,12 @@ class TableTest < ActiveSupport::TestCase
table1.slug = table2.slug
assert_not table1.valid?
end
test "creating adds UUID and slug" do
table = Table.create(name: "New table", game_system: GameSystem.first, owner: User.first)
table.reload
assert_not_nil table.uuid
assert_not_nil table.slug
assert table.slug.start_with?("new-table")
end
end