自定义验证导致插入/ 4

问题描述 投票:0回答:1

我不明白为什么会收到此错误:

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
elixir phoenix-framework ecto
1个回答
0
投票

似乎您忘记了当validate_presents_of_parent为真时,从:is_country返回(不变的)变更集。

  def validate_presents_of_parent(changeset) do
    # Only a country doesn't have a parent.
    if get_field(changeset, :is_country) do
      changeset
    else
      assoc_constraint(changeset, :parent_location)
    end
  end
© www.soinside.com 2019 - 2024. All rights reserved.