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



当尝试在UserMandate之间建立1到n的关系时,编译器会抛出一个参数错误:

== 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

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

环境

长生不老药 1.4.2

Erlang/OTP 19

Ecto 2.1.4

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

由于我想要 UUID 作为我的密钥,所以我不得不改用@primary_key {:id, Ecto.UUID, autogenerate: true}

最新更新