gpt4 book ai didi

elixir - 这个 Ecto Constraint Error 试图告诉我什么?

转载 作者:行者123 更新时间:2023-12-04 22:19:44 24 4
gpt4 key购买 nike

** (Ecto.ConstraintError) constraint error when attempting to insert model:

* foreign_key: matches_person_id_fkey

这是我的架构和迁移:
def change do
create table(:matches) do
add :percentage, :float
add :person_id, references(:persons)
add :star_id, references(:stars)

timestamps
end
create index(:matches, [:person_id])
end

schema "matches" do
field :percentage, :float
belongs_to :person, Person
belongs_to :star, Star

timestamps
end

我在调用 Repo.insert(changeset) 时使用的变更集是:
%Ecto.Changeset{action: nil,
changes: %{percentage: 0.513657, person_id: 55, star_id: 1}, constraints: [],
errors: [], filters: %{},
model: %App.Match{__meta__: #ecto.Schema.Metadata<:built>, id: nil,
inserted_at: nil, percentage: nil,
person: #ecto.Association.NotLoaded<association :person is not loaded>,
person_id: nil,
star: #ecto.Association.NotLoaded<association :star is not loaded>,
star_id: nil, updated_at: nil}, optional: [], opts: [],
params: %{"percentage" => 0.513657, "person_id" => 55, "star_id" => 1},
prepare: [], repo: nil, required: [:percentage, :person_id, :star_id],
types: %{id: :id, inserted_at: Ecto.DateTime, percentage: :float,
person_id: :id, star_id: :id, updated_at: Ecto.DateTime}, valid?: true,
validations: []}

我不确定发生了什么,或者我是否在此过程中进行了更改,因为这在以前是有效的。该错误似乎表明我需要一个 person_id,我就是这样做的。

编辑:根据要求,我为匹配插入所做的函数调用
...
Repo.transaction(fn ->
case Repo.insert(person_changeset) do
{:ok, person} ->
Match.create(person.id)
{:error, _}
Repo.rollback(:no_bueno)
end
end)

def create(person_id) do
...
params = %{"person_id" => person.id, "percentage" => percentage, "star_id" => star.id}
changeset = __MODULE__.changeset(%__MODULE__{}, params)
case Repo.insert(changeset) do
{:ok, _person} ->
IO.puts "success"
{:error, _changeset} ->
Repo.rollback(:no_bueno)
end
end

最佳答案

此错误告诉您 ID 为 55 的人不存在。

有点相关,在您的迁移中,不需要以下内容:

create index(:matches, [:person_id])

references/2 时会自动创建索引:
add :person_id, references(:persons)

如果要填充变更集中的错误,则需要添加 foreign_key_constraint/3到您的变更集:
cast(match, params, ~w(person_id), ~w())
|> foreign_key_constraint(:person_id)

虽然与问题没有直接关系,但看起来您可能正在使用 Repo在你的模型中。请查看 Should I use Ecto.Repo in Controller or Model for Elixir Phoenix?

关于elixir - 这个 Ecto Constraint Error 试图告诉我什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34857669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com