自定义验证导致 insert/4

Custom validation leads to an insert/4

我不明白为什么会出现此错误:

Abc.Maps.Location.create_location(%{name: "USA", is_country: true})
** (FunctionClauseError) no function clause matching in Ecto.Repo.Schema.insert/4 

我知道没有 insert/4 但我不明白为什么 validate_presents_of_parent/1 首先会造成问题。我的错误是什么?

我想验证 parent_location 是否存在,以防 location 不是国家/地区。

defmodule Abc.Maps.Location do
  use Ecto.Schema
  import Ecto.Changeset

  schema "locations" do
    field(:is_country, :boolean, default: false)
    field(:is_federal_state, :boolean, default: false)
    field(:name, :string)
    belongs_to :parent_location, Abc.Maps.Location

    timestamps()
  end

  @doc false
  def changeset(location, attrs) do
    location
    |> cast(attrs, [
      :name,
      :is_country,
      :is_federal_state,
      :parent_location_id
    ])
    |> validate_required([:name])
    |> validate_presents_of_parent()
  end

  def validate_presents_of_parent(changeset) do
    # Only a country doesn't have a parent.
    unless get_field(changeset, :is_country) do
      assoc_constraint(changeset, :parent_location)
    end
  end
end

:is_country 为真时,您似乎忘记了 return 来自 validate_presents_of_parent 的(未更改的)变更集。您还需要验证 :parent_location_id

  def validate_presents_of_parent(changeset) do
    # Only a country doesn't have a parent.
    if get_field(changeset, :is_country) do
      changeset
    else
      changeset
      |> validate_required([:parent_location_id])
      |> assoc_constraint(:parent_location)
    end
  end