Ecto - Conditional validate_required

Hi,

I have a question_type field which determines what part of a struct is required. If it is :text then the :text field is required, if it is :option then the :option_id field is required. However, doing what I’ve done below doesn’t seem to be working, any idea what I’m doing wrong? Thanks

  def changeset(response, attrs) do
    response
    |> cast(attrs, [:text, :question_id, :option_id, :question_type])
    |> cast_assoc(:sub_response, with: &SubResponse.changeset/2)
    |> validate_required([:question_id], message: "Please enter a value.")
    |> validate_by_type()
  end

  defp validate_by_type(changeset) do
    case get_field(changeset, :question_type) do
      :text ->
        changeset
        |> validate_required([:text], message: "Please enter a value.")

      :option ->
        changeset |> validate_required([:option_id], message: "Please enter a value.")

      _ ->
        changeset
    end
  end
3 Likes

What is the type of the question_type field in your schema? The only way it seems this could go wrong is if get_field(changeset, :question_type) isn’t returning an atom…

1 Like

You’re right, thanks!