Ich habe Xyz
, die entweder eine country_id
, eine federal_state_id
oder eine city_id
hat. Aber nur einer von ihnen (nicht alle drei und auch nicht zwei). Wie kann ich eine Validierung dafür durchführen? Und wie kann ich ein assoc_constraint/1
für dieses Feld nur für dieses tun?validate_required für eins von drei
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
Wow, wusste nicht, dass Sie in eine case-Anweisung pipen können. Aber es macht definitiv Sinn. – Phillipp