0.15"}, {:phoenix_ecto, "~> 1.0.0"}, {:postgrex, ">= 0.0.0"}, {:phoenix-6ren">
gpt4 book ai didi

elixir - Phoenix _ecto : error when loading assoc

转载 作者:行者123 更新时间:2023-12-02 06:31:21 26 4
gpt4 key购买 nike

具有以下混合部门:

[{:phoenix, "~> 0.15"},
{:phoenix_ecto, "~> 1.0.0"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.1"},
{:phoenix_live_reload, "~> 0.5", only: :dev},
{:cowboy, "~> 1.0"}]

以及以下型号:

# foo.ex
has_many: :bars, App.Bar

# bar.ex
belongs_to: :foo, App.Foo

当数据库中已插入 Foo 时,尝试预加载 bars 时出现错误:

Repo.all(Foo) |> Repo.preload(:bars)

产量:

** (FunctionClauseError) no function clause matching in Postgrex.Extensions.Binary.encode/4
(ecto) lib/ecto/repo/preloader.ex:49: Ecto.Repo.Preloader.do_preload/4

当尚未插入 Foo 时,它不会产生任何错误(只是 [])。

Bar 迁移:

defmodule App.Repo.Migrations.CreateBar do
use Ecto.Migration

def change do
create table(:bars) do
add :title, :string
add :foo_id

timestamps
end

create index(:bars, [:foo_id])
end
end

最佳答案

您在迁移中缺少 :foo_id 类型。

尝试以下操作:

defmodule App.Repo.Migrations.CreateBar do
use Ecto.Migration

def change do
create table(:bars) do
add :title, :string
add :foo_id, references(:foos)

timestamps
end

create index(:bars, [:foo_id])
end
end

您可以在 http://hexdocs.pm/ecto/0.15.0/Ecto.Migration.html 阅读迁移文档。

关于elixir - Phoenix _ecto : error when loading assoc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966119/

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