From 191684a11cb965c6e4826d0601fd1e10663082c4 Mon Sep 17 00:00:00 2001 From: Manuel Bustillo Date: Wed, 24 Jul 2024 20:37:14 +0200 Subject: [PATCH] Persist table distributions --- app/models/tables_arrangement.rb | 1 + app/services/tables/distribution.rb | 26 ++++++++++++++++++- ...240724181756_create_tables_arrangements.rb | 1 + db/schema.rb | 1 + lib/tasks/vns.rake | 4 +++ 5 files changed, 32 insertions(+), 1 deletion(-) diff --git a/app/models/tables_arrangement.rb b/app/models/tables_arrangement.rb index 0bf9996..1be3ec3 100644 --- a/app/models/tables_arrangement.rb +++ b/app/models/tables_arrangement.rb @@ -1,2 +1,3 @@ class TablesArrangement < ApplicationRecord + has_many :seats end diff --git a/app/services/tables/distribution.rb b/app/services/tables/distribution.rb index b8a9997..aa87de5 100644 --- a/app/services/tables/distribution.rb +++ b/app/services/tables/distribution.rb @@ -1,6 +1,6 @@ module Tables class Distribution - attr_reader :tables + attr_accessor :tables def initialize(min_per_table:, max_per_table:) @min_per_table = min_per_table @@ -29,6 +29,30 @@ module Tables end.join("\n") end + def deep_dup + self.class.new(min_per_table: @min_per_table, max_per_table: @max_per_table).tap do |new_distribution| + new_distribution.tables = @tables.map(&:dup) + end + end + + def save! + ActiveRecord::Base.transaction do + arrangement = TablesArrangement.create! + + records_to_store = [] + + tables.each_with_index do |table, table_number| + table.each do |person| + records_to_store << { guest_id: person.id, tables_arrangement_id: arrangement.id, table_number: } + end + end + + Seat.insert_all!(records_to_store) + + arrangement.update!(discomfort:) + end + end + private def local_discomfort(table) diff --git a/db/migrate/20240724181756_create_tables_arrangements.rb b/db/migrate/20240724181756_create_tables_arrangements.rb index 358c623..c05f6dc 100644 --- a/db/migrate/20240724181756_create_tables_arrangements.rb +++ b/db/migrate/20240724181756_create_tables_arrangements.rb @@ -1,6 +1,7 @@ class CreateTablesArrangements < ActiveRecord::Migration[7.1] def change create_table :tables_arrangements, id: :uuid do |t| + t.integer :discomfort t.timestamps end diff --git a/db/schema.rb b/db/schema.rb index fa7e73b..08c4026 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -46,6 +46,7 @@ ActiveRecord::Schema[7.1].define(version: 2024_07_24_181853) do end create_table "tables_arrangements", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t| + t.integer "discomfort" t.datetime "created_at", null: false t.datetime "updated_at", null: false end diff --git a/lib/tasks/vns.rake b/lib/tasks/vns.rake index dd5a942..c33de67 100644 --- a/lib/tasks/vns.rake +++ b/lib/tasks/vns.rake @@ -12,5 +12,9 @@ namespace :vns do engine.target_function(&:discomfort) best_solution = engine.run + + binding.pry + + best_solution.save! end end