使用 Ecto.Schema.has_many 时出现参数错误

argument error when using Ecto.Schema.has_many

当试图在 UserMandate 之间建立一对多的关系时,编译器抛出参数错误:

== Compilation error on file lib/platform/mandate.ex ==
** (ArgumentError) argument error
    (ecto) lib/ecto/association.ex:474: Ecto.Association.Has.get_ref/3
    (ecto) lib/ecto/association.ex:424: Ecto.Association.Has.struct/3
    (ecto) lib/ecto/schema.ex:1679: Ecto.Schema.association/5
    (ecto) lib/ecto/schema.ex:1474: Ecto.Schema.__has_many__/4
    lib/platform/mandate.ex:10: (module)
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1

mandate.ex(节选):

defmodule Platform.Mandate do
  use Ecto.Schema

  @primary_key false
  @derive {Poison.Encoder, only: [:name, :rules, :users, :id]}
  schema "mandates" do
    field(:id, Ecto.UUID, primary_key: true)
    field(:name, :string)

    has_many(:users, Platform.User, foreign_key: :mandate_id)

    embeds_many(:rules, __MODULE__.PermissionRule)

    timestamps()
  end
end

user.ex(节选):

defmodule Platform.User do
  @moduledoc false
  use Ecto.Schema
  use Coherence.Schema

  schema "users" do
    field :name, :string
    field :email, :string
    belongs_to(:mandate, Platform.Mandate, references: :mandate_id)
    coherence_schema()

    timestamps()
  end
end

如果我注释掉 mandate.ex 中的 has_many 调用,它会编译,但显然我不能使用预加载和关联。

环境

长生不老药 1.4.2

Erlang/OTP 19

2.1.4

我发现当您想将该键用作另一个 table 中的外键时,使用 @primary_key false 是错误的。

因为我想为我的密钥使用 UUID,所以我不得不使用 @primary_key {:id, Ecto.UUID, autogenerate: true}