diff --git a/app/models/account.rb b/app/models/account.rb index 29912092c..7e7977967 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -11,6 +11,7 @@ class Account < ApplicationRecord has_many_attached :uploads + before_create :assign_external_account_id after_create :create_join_code validates :name, presence: true @@ -35,4 +36,9 @@ class Account < ApplicationRecord def system_user users.where(role: :system).first! end + + private + def assign_external_account_id + self.external_account_id ||= ExternalAccount.create!.id + end end diff --git a/app/models/external_account.rb b/app/models/external_account.rb new file mode 100644 index 000000000..11b5c4d5e --- /dev/null +++ b/app/models/external_account.rb @@ -0,0 +1,5 @@ +# This is meant to provide a sequential ID for +external_account_id+ when creating +# accounts without one. The SaaS version of the app uses that column, but most apps +# can just go with the default handling here. +class ExternalAccount < ApplicationRecord +end diff --git a/db/migrate/20251127000001_create_external_accounts.rb b/db/migrate/20251127000001_create_external_accounts.rb new file mode 100644 index 000000000..8dee2feaf --- /dev/null +++ b/db/migrate/20251127000001_create_external_accounts.rb @@ -0,0 +1,15 @@ +class CreateExternalAccounts < ActiveRecord::Migration[8.0] + def up + create_table :external_accounts do |t| + end + + max_id = Account.maximum(:external_account_id) || 0 + if max_id > 0 + execute "INSERT INTO external_accounts (id) VALUES (#{max_id})" + end + end + + def down + drop_table :external_accounts + end +end diff --git a/test/models/account_test.rb b/test/models/account_test.rb index 7b212e8ab..57f2406be 100644 --- a/test/models/account_test.rb +++ b/test/models/account_test.rb @@ -59,4 +59,22 @@ class AccountTest < ActiveSupport::TestCase account.system_user end end + + test "external_account_id auto-increments on creation" do + account1 = Account.create!(name: "First Account") + account2 = Account.create!(name: "Second Account") + + assert_not_nil account1.external_account_id + assert_not_nil account2.external_account_id + assert_equal account1.external_account_id + 1, account2.external_account_id + end + + test "external_account_id can be overridden without creating sequence entry" do + custom_id = Account.last.id + 99999 + + assert_no_difference -> { ExternalAccount.count } do + account = Account.create!(name: "Custom ID Account", external_account_id: custom_id) + assert_equal custom_id, account.external_account_id + end + end end