From 5a36e57b9fc461f91f3e3ab0d7988f2655add5ca Mon Sep 17 00:00:00 2001 From: Sebastian Serth Date: Mon, 20 Mar 2023 23:43:53 +0100 Subject: [PATCH] Reuse ActiveRecord object after creating StructuredErrorAttributes With these changes, the newly created StructuredError will have all StructuredErrorAttributes preloaded, thus speeding up further access to this association. --- app/models/structured_error.rb | 12 +++++++----- app/models/structured_error_attribute.rb | 5 ++--- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/app/models/structured_error.rb b/app/models/structured_error.rb index 9ce2f00a..3291423d 100644 --- a/app/models/structured_error.rb +++ b/app/models/structured_error.rb @@ -7,11 +7,13 @@ class StructuredError < ApplicationRecord has_many :structured_error_attributes def self.create_from_template(template, message_buffer, submission) - instance = create(error_template: template, submission:) - template.error_template_attributes.each do |attribute| - StructuredErrorAttribute.create_from_template(attribute, instance, message_buffer) - end - instance + create( + error_template: template, + submission:, + structured_error_attributes: template.error_template_attributes.filter_map do |attribute| + StructuredErrorAttribute.create_from_template(attribute, message_buffer) + end + ) end def hint diff --git a/app/models/structured_error_attribute.rb b/app/models/structured_error_attribute.rb index 85aee7e3..8f42f5b5 100644 --- a/app/models/structured_error_attribute.rb +++ b/app/models/structured_error_attribute.rb @@ -4,13 +4,12 @@ class StructuredErrorAttribute < ApplicationRecord belongs_to :structured_error belongs_to :error_template_attribute - def self.create_from_template(attribute, structured_error, message_buffer) + def self.create_from_template(attribute, message_buffer) value = nil result = message_buffer.match(attribute.regex) if !result.nil? && result.captures.size.positive? value = result.captures[0] end - create(structured_error:, error_template_attribute: attribute, value:, - match: !result.nil?) + create(error_template_attribute: attribute, value:, match: !result.nil?) end end