key:找不到user_id.Elixir Preload问题

时间:2017-11-22 03:18:49

标签: elixir phoenix-framework

我在构建联盟结构时尝试添加user_id,但它给了我这个错误:

** (KeyError) key :user_id not found in: %{__meta__: #Ecto.Schema.Metadata<:built, "leagues">, __struct__: Statcasters.Schema.League, id: nil, inserted_at: nil, name: nil, teams: #Ecto.Association.NotLoaded<association :teams is not loaded>, updated_at: nil, users: #Ecto.Association.NotLoaded<association :users is not loaded>, users_id: nil}
(stdlib) :maps.update(:user_id, {{:., [line: 14], [{:user, [line: 14], nil}, :id]}, [line: 14], []}, %{__meta__: #Ecto.Schema.Metadata<:built, "leagues">, __struct__: Statcasters.Schema.League, id: nil, inserted_at: nil, name: nil, teams: #Ecto.Association.NotLoaded<association :teams is not loaded>, updated_at: nil, users: #Ecto.Association.NotLoaded<association :users is not loaded>, users_id: nil})

这是我的控制器:

LEAGUE CONTROLLER

  def new(conn, _params) do
    user = Repo.get!(User, conn.assigns.current_user.id)
    changeset = %League{user_id: user.id}
      |> League.changeset()

    render(conn, "new.html", changeset: changeset)
  end

模型

league.ex
  schema "leagues" do
    field :name, :string
    has_many :teams, Statcasters.Teams.Team
    belongs_to :users, Statcasters.Coherence.User

    timestamps()
  end
user.ex
  schema "users" do
    field :name, :string
    field :email, :string
    coherence_schema()
    has_many :leagues, Statcasters.Schema.League

    timestamps()
  end

我需要使用Repo.preload吗?我不确定它告诉我要做什么?

2 个答案:

答案 0 :(得分:6)

如果您仔细查看错误,则表示未找到 :user_id 。事实上,它并没有出现在地图中,但:users_id确实存在。这只能意味着你有一个名为users而不是user的关系,这正是问题所在。 belongs_to :users应为belongs_to :user

答案 1 :(得分:1)

如果您点击此链接https://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3, 你会看到在Ecto.Schema =&gt;下提到它。函数=&gt; belongs_to / 3 =&gt;选项

belongs_to(name, queryable, opts \\ [])

  

:foreign_key - 设置外键字段名称,默认为以_id为后缀的关联名称。例如,belongs_to:company将定义外键:company_id

在您的情况下,belongs_to :user将定义:user_id

的外键