Elixir 自定义验证导致插入/4
我不明白为什么会出现这样的错误:Elixir 自定义验证导致插入/4,elixir,phoenix-framework,ecto,Elixir,Phoenix Framework,Ecto,我不明白为什么会出现这样的错误: Abc.Maps.Location.create_location(%{name: "USA", is_country: true}) ** (FunctionClauseError) no function clause matching in Ecto.Repo.Schema.insert/4 我知道没有insert/4,但我不明白为什么validate\u呈现\u parent/1的\u首先会产生问题。我犯了什么错 如果位置不是国家/地区,我想验证是否
Abc.Maps.Location.create_location(%{name: "USA", is_country: true})
** (FunctionClauseError) no function clause matching in Ecto.Repo.Schema.insert/4
我知道没有insert/4
,但我不明白为什么validate\u呈现\u parent/1的\u
首先会产生问题。我犯了什么错
如果位置
不是国家/地区,我想验证是否存在父位置
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\u country
为true时,您似乎忘记返回父项的validate\u presents\u中的(未更改的)变更集。您还需要验证:父位置\u 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
很确定你的意思是验证\u父对象的存在性\u
。孩子们。。总是检查他们收到的礼物是否是真的眨眼: