roadmap icon indicating copy to clipboard operation
roadmap copied to clipboard

Fix and Refactor Querying of `template.phases` and Associations Within `OrgAdmin TemplatesController`

Open aaronskiba opened this issue 1 year ago • 0 comments

Fixes # .

Changes proposed in this PR:

  • Address ambiguity and remove one-to-many columns from .select() clause ca52b915253cd412e7a50372b730586965b56a98

    • Prior to this commit, both 'phases.title' and 'sections.title' were included in the .select() clause. Since 'sections.title' was listed after 'phases.title', phases.first.title, would evaluate to the sections.title value.
    • A phase can have multiple sections, questions, and question_options, so including columns like sections.title in .select() is not appropriate.
    • No additional handling is needed since we're already using .includes(sections: { questions: :question_options }) to preload the associations, and phase.sections.each etc. handles the associations properly within the view.
  • Refactor fetching of template.phases b18a454964e559bb73f09d78f0f314187264089c

    • There were identical phases queries within the view and edit actions. This refactor makes the query accessible by calling the fetch_template_phases method.
  • Fix and refactor ordering of template associations c7921b4694e01eddc0fbb02792a09e068320f0e7

    • Removed .order() as it was only applied to the main phases query and did not guarantee the order of associated records (e.g., question_options), which are loaded in separate queries.
    • default_scope { order(number: :asc) } already exists for the Phase, Section, and Question models, ensuring the desired ordering by default.
    • The QuestionOption model includes scope :by_number, -> { order(:number) }, which is now explicitly applied when fetching the question_options association to enable proper ordering.
    • .order() must've been auto-including :id in the .select() clause. Since it is required, we are explicitly adding it now.
  • Refactor/optimise check for question_options db92f3b0cbcc19ab86a8699dbdccc4c4b87b98be

    • Replaced .length > 0 with .any? to improve readability and performance.
    • .any? is more efficient for checking if a collection has elements, especially for ActiveRecord associations, as it doesn't require loading the entire collection into memory.

aaronskiba avatar Jan 08 '25 21:01 aaronskiba