Update Tables::Distribution#save! to consider that the distribution may already be persisted

This commit is contained in:
Manuel Bustillo 2025-09-08 15:51:43 +02:00
parent dd14a96e98
commit ac659bef86
3 changed files with 42 additions and 4 deletions

View File

@ -29,5 +29,5 @@
class Seat < ApplicationRecord
acts_as_tenant :wedding
belongs_to :guest
belongs_to :table_arrangement
belongs_to :tables_arrangement
end

View File

@ -12,13 +12,14 @@ module Tables
end
end
attr_accessor :tables, :min_per_table, :max_per_table, :hierarchy
attr_accessor :tables, :min_per_table, :max_per_table, :hierarchy, :tables_arrangement_id
def initialize(min_per_table:, max_per_table:, hierarchy: AffinityGroupsHierarchy.new)
def initialize(min_per_table:, max_per_table:, hierarchy: AffinityGroupsHierarchy.new, tables_arrangement_id: nil)
@min_per_table = min_per_table
@max_per_table = max_per_table
@hierarchy = hierarchy
@tables = []
@tables_arrangement_id = tables_arrangement_id
end
def random_distribution(people, random: Random.new)
@ -50,7 +51,11 @@ module Tables
def save!
ActiveRecord::Base.transaction do
arrangement = TablesArrangement.create!
arrangement = TablesArrangement.find_or_create_by!(id: tables_arrangement_id)
self.tables_arrangement_id = arrangement.id
arrangement.seats.delete_all
records_to_store = []

View File

@ -6,6 +6,39 @@ require 'rails_helper'
module Tables
RSpec.describe Distribution do
describe '#save!' do
around do |example|
ActsAsTenant.with_tenant(create(:wedding)) do
example.run
end
end
let(:people) { create_list(:guest, 2, status: :invited) }
let(:distribution) do
described_class.new(min_per_table: 5, max_per_table: 10).tap{|d| d.random_distribution(people)}
end
context 'when tables_arrangement_id is nil' do
it { expect { distribution.save! }.to change { TablesArrangement.count }.by(1) }
it { expect { distribution.save! }.to change { Seat.count }.by(2) }
end
context 'when tables_arrangement_id is set' do
before do
existing_arrangement = TablesArrangement.create!
existing_arrangement.seats.create!(guest: people.first, table_number: 1)
distribution.tables_arrangement_id = existing_arrangement.id
end
it { expect { distribution.save! }.not_to change { TablesArrangement.count } }
it { expect { distribution.save! }.to change { Seat.count }.by(1) }
end
end
describe '#random_distribution' do
subject(:distribution) { described_class.new(min_per_table: 5, max_per_table: 10) }