Example Code Refactoring
The snippet can be accessed without any authentication.
Authored by
Dave Krupinski
The following code needs to be updated and refactored to work in a modified workflow.
Current Code Operational Notes
-
QuestionImage
can be created without an existingQuestion
record. - An array of
image_ids
must be maintained and passed to method. - The
assign_images
must be invoked when modifyingQuestion
.
Updated Requirements
-
QuestionImage
can still be created without an existingQuestion
record. - Inserted images will added to
body
with the format of/question/images/:id.:format
. - The
body
should be the sole source of truth for the relatedQuestionImage
record usage. - Image assignment should a lifecycle event.
- Unused images should be removed.
# frozen_string_literal: true
class Question < ApplicationRecord
has_many :images, class_name: 'QuestionImage', dependent: :destroy
def assign_images(image_ids = [])
return if image_ids.empty?
image_ids_found = \
QuestionImage
.where(question_id: nil)
.where(id: image_ids)
.select { |i| body.index i.path }
.map(&:id)
QuestionImage
.where(id: image_ids_found.flatten)
.update_all(question_id: id)
end
end
Please register or sign in to comment