Current section

Files

Jump to
ami lib ami question.ex
Raw

lib/ami/question.ex

defmodule Ami.Question do
use Ecto.Schema
import Ecto.{
Query,
Changeset
}
alias Ami.{
Repo,
Quiz,
Answer
}
schema "questions" do
field(:correct_answers, :string)
field(:value, :string)
field(:label, :string)
field(:position, :integer)
field(:answer_type, :integer)
belongs_to(:quiz, Quiz)
has_many(:answers, Answer, on_delete: :delete_all, on_replace: :delete)
end
@doc """
Extract the values as array from question values string
"""
def extract_options(value) when is_nil(value), do: []
def extract_options(value) do
String.replace(value, ~r/\[|\]/, " ")
|> String.split("\",")
|> Enum.map(&String.replace(&1, ~r/\"/, ""))
|> Enum.map(&String.trim(&1))
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:correct_answers, :value, :label, :position, :answer_type, :quiz_id])
|> validate_required([
:label,
:answer_type
])
|> cast_assoc(:answers)
|> case do
%{valid?: false, errors: errors} = changeset when errors == [
label: {"can't be blank", [validation: :required]},
answer_type: {"can't be blank", [validation: :required]}
] ->
%{changeset | action: :ignore}
changeset ->
changeset
end
end
def answer_types do
[
{"Single correct answer", 0},
{"Multiple correct answers", 1}
# {"Complete the text", 2},
# {"Matching terms to terms", 3}
]
end
def stringify_answer_type(question) do
{str, val} =
Enum.find(__MODULE__.answer_types(), fn {str, val} -> val == question.answer_type end)
str
end
def update_position(id, position) do
Repo.get!(__MODULE__, id)
|> change(%{position: position})
|> Repo.update()
end
end