Dynamically preload entries based on a column value

I want to dynamically preload entries from different tables based on a column value.

Writing a quizzing application where Question can have multiple choices, stored in different tables. Preload should happen based on the question type column in Question table. Can anyone guide me on how to achieve this

Question -> single_choices
-> multiple_choices
-> FIB_choices
-> matching_choices

Create a function (i.e. preload_details) with multiple bodies. Pattern match on the question types and preload the rest depending on the type.

I have a below code which extracts all questions and preloads choices, this holds good when there is only one kind of choice table. What if there are other choice tables (true/false, FIB, matching) stored in other tables. How can we dynamically preload choices based on question.type indicator. Also how Question scheme will map has_many relations with other choice tables.

If you have any other approach to tackle this problem, please do highlight. thanks

has_many :choices, Evaluto.Choice, on_delete: :delete_all

defp load_questions(company_id) do
question_query = from q in Question,
where: q.company_id == ^company_id,
order_by: [desc: q.inserted_at],
preload: :choices
question_query
|> Repo.all()
end

How about preloading all of those tables (or even better joining them to a single db query).

Then you can push the need to select by type to the runtime:

has_many :multiple_choice, Evaluto.MulipleChoice, on_delete: :delete_all
has_many :single_choice, Evaluto.SingleChoice, on_delete: :delete_all

defp get_question_details(%Question{type: :single_choice} = question), 
    do: question.single_choice
defp get_question_details(%Question{type: :multiple_choice} = question), 
    do: question.multiple_choice
1 Like