validate_required for one out of three

Viewed 350

I have Xyz which either has a country_id, a federal_state_id or a city_id. But only one of them (not all three and not two either). How can I do a validation for that? Plus how can I do an assoc_constraint/1 for that field only for that one?

defmodule Example.Location.Xyz do
  use Ecto.Schema
  import Ecto.Changeset
  alias Example.Location.Xyz

  schema "xyzs" do
    field :name, :string
    belongs_to :country, Example.Location.Country
    belongs_to :federal_state, Example.Location.FederalState
    belongs_to :city, Example.Location.City

    timestamps()
  end

  @doc false
  def changeset(%Xyz{} = xyz, attrs) do
    school
    |> cast(attrs, [:name, :country_id, :federal_state_id, :city_id])
    |> validate_required([:name, :country_id, :federal_state_id, :city_id])
    |> assoc_constraint(:country)
    |> assoc_constraint(:federal_state)
    |> assoc_constraint(:city)
  end
end
1 Answers

I'd create a function that checks that exactly 1 of the 3 fields is present and also add the right assoc_constraint:

@doc false
def changeset(%Xyz{} = xyz, attrs) do
  school
  |> cast(attrs, [:name, :country_id, :federal_state_id, :city_id])
  |> validate_required([:name])
  |> validate_one_of_present([:country_id, :federal_state_id, :city_id])
end

def validate_one_of_present(changeset, fields) do
  fields
  |> Enum.filter(fn field ->
    # Checks if a field is "present".
    # The logic is copied from `validate_required` in Ecto.
    case get_field(changeset, field) do
      nil -> false
      binary when is_binary(binary) -> String.trim_leading(binary) == ""
      _ -> true
    end
  end)
  |> case do
    # Exactly one field was present.
    [field] ->
      without_id = field |> Atom.to_string |> String.replace_suffix("_id", "") |> String.to_existing_atom
      assoc_constraint(changeset, without_id)
    # Zero or more than one fields were present.
    _ ->
      add_error(changeset, hd(fields), "expected exactly one of #{inspect(fields)} to be present")
  end
end

Code is untested, let me know if you find any errors!

Related