Skip to content
Snippets Groups Projects

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 existing Question record.
  • An array of image_ids must be maintained and passed to method.
  • The assign_images must be invoked when modifying Question.

Updated Requirements

  • QuestionImage can still be created without an existing Question 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 related QuestionImage record usage.
  • Image assignment should a lifecycle event.
  • Unused images should be removed.
Edited
exercise.rb 488 B
# 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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment