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