【问题标题】:Cannot expand struct - elixir/phoenix无法扩展结构 - 长生不老药/凤凰
【发布时间】:2019-10-21 21:51:31
【问题描述】:

我正在尝试在屏幕上显示一个表单。但是当我尝试启动服务器时,我不断收到此错误。 locations_controller.ex == ** (CompileError) web/controllers/locations_controller.ex:5: Locations.__struct__/1 is undefined, cannot expand struct Locations。顺便说一句,我是 elixir 的新手,所以我可能做错了一些非常明显的错误。

这是我的代码:

locations.controller.ex

 def new(conn, _params) do
    changeset = Locations.changeset(%Locations{})

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

  def create(conn, %{"locations" => %{ "start" => start, "end" => finish }}) do
    changeset = %AwesomeLunch.Locations{start: start, end: finish}
    Repo.insert(changeset)

    redirect conn, to: locations_path(conn, :index)
  end

查看

<h1>Hey There</h1>

<%= form_for @changeset, locations_path(@conn, :create), fn f -> %>

  <label>
    Start: <%= text_input f, :start %>
  </label>

  <label>
    End: <%= text_input f, :end %>
  </label>

  <%= submit "Pick An Awesome Lunch" %>

<% end %>

型号

    defmodule AwesomeLunch.Locations do
  use AwesomeLunch.Web, :model

  use Ecto.Schema
  import Ecto.Changeset

  schema "locations" do
    field :start
    field :end
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:start, :end])
    |> validate_required([:start, :end])
  end
end

就像我说的那样,我收到了这个错误:

    locations_controller.ex ==
** (CompileError) web/controllers/locations_controller.ex:5: Locations.__struct__/1 is undefined, cannot expand struct Locations

【问题讨论】:

  • 与解决问题/问题没有直接关系,但据我了解,Phoenix 的最佳做法是以单数形式命名您的域对象,而不是复数形式(例如。 defmodule AwesomeLunch.LocationLocationController 等)。这样你就不会像在 Rails 世界中那样有时指单数有时指复数的令人困惑的约定。

标签: struct elixir phoenix-framework


【解决方案1】:

Elixir 中的模块需要用它们的全名或alias 来引用。您可以将所有Locations 更改为AwesomeLunch.Locations,或者如果您想使用更短的名称,您可以在该模块中调用alias

defmodule AwesomeLunch.LocationsController do
  alias AwesomeLunch.Locations

  ...
end

【讨论】:

    【解决方案2】:

    我正在开发一个伞形项目,但有时会遇到同样的错误。

    如果您创建一个在App1 中声明的结构,并希望在App2 中使用它,您必须将App1 添加到App2 作为依赖项。如果您不这样做并且如果在App1 之前加载了App2,则会发生错误。

    示例: {:app1, in_umbrella: true}

    【讨论】:

      【解决方案3】:

      我遇到了同样的错误,对我来说,它可以通过这种方式配置控制器:

      defmodule AwesomeLunch.LocationsController do
        use AwesomeLunch.Web, :controller
      
        alias AwesomeLunch.Locations
      
        ...
      end
      

      【讨论】:

        猜你喜欢
        • 2021-01-29
        • 1970-01-01
        • 2016-02-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多