【问题标题】:__struct__/1 is undefined, cannot expand struct Gazette.User__struct__/1 未定义,无法扩展 struct Gazette.User
【发布时间】:2018-07-19 04:54:03
【问题描述】:

我正在构建一个 Phoenix 1.3 应用程序,但是按照 1.2 Pheonix 教程,我运行了不推荐使用的命令,例如 mix phoenix.gen.model

我不确定它是否已链接,但现在我收到此错误:

== Compilation error in file lib/gazette_web/controllers/user_controller.ex ==
** (CompileError) lib/gazette_web/controllers/user_controller.ex:12: Gazette.User.__struct__/1 is undefined, cannot expand struct Gazette.User
    lib/gazette_web/controllers/user_controller.ex:11: (module)
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:121: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1

这是我的 user_controller.ex 文件:

defmodule Gazette.UserController do
  use GazetteWeb, :controller

  alias Gazette.User

  def show(conn, %{"id" => id}) do
    user = Repo.get!(User,id)
    render(conn, "show.html", user: user)
  end

  def new(conn, _params) do
    changeset = User.changeset(%User{})
    render conn, "new.html", changeset: changeset
  end

  def create(conn, %{"user" => user_params}) do
    # here will be an implementation
  end
end

这是我的模型/user.ex 文件:

defmodule Gazette.User do
  use Gazette.Web, :model

  schema "users" do
    field :email, :string
    field :name, :string
    field :password, :string, virtual: true
    field :password_hash, :string
    field :is_admin, :string
    field :is_writer, :string

    has_many :posts, Gazette.Post

    timestamps()
  end

  @required_fields ~w(email name)a
  @optional_fields ~w(is_admin is_writer)a

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, @required_fields ++ @optional_fields)
    |> validate_required(@required_fields)
  end
end

有什么想法吗?

【问题讨论】:

  • 在提出新问题之前,您必须将答案标记为正确,或者提供您自己的答案并将其标记为正确。

标签: elixir phoenix-framework ecto elixir-mix


【解决方案1】:

您的Gazette.User 是一个常规模块,它不会自动转换为结构。要从中创建 Ecto 架构,您需要:

use Ecto.Schema

我不确定use Gazette.Web, :model 做了什么,但我相信它已被弃用。定义模式时最好是明确的。

您可能还希望/需要:

import Ecto.Changeset
import Ecto.Query

此代码可能是使用旧的 mix phx.gen.model 任务自动生成的。相反,您想使用mix phx.gen.schema 来获得正确的样板文件。

【讨论】:

  • 这确实是问题所在。 Gazette.Web 已弃用;我添加了`use Ecto.Schema import Ecto.Changeset alias Gazette.User`,但我遇到了一些新错误。由于我刚开始我的项目,我只是从头开始并使用正确的混合命令在我的数据库中创建我的表。
  • 是的, :model 在 2015 年 Ecto 1.1 发布时已被弃用。那些旧教程很危险!
  • 啊,两个小时!!文档太混乱了:(
猜你喜欢
  • 2021-12-09
  • 2020-08-27
  • 1970-01-01
  • 2019-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多