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.
This commit is contained in:
Sebastian Serth
2023-03-20 23:43:53 +01:00
parent baa62276fe
commit 5a36e57b9f
2 changed files with 9 additions and 8 deletions

View File

@ -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

View File

@ -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