问题 无法扩展struct - elixir / phoenix


我正在尝试在屏幕上显示一个表单。但是当我尝试启动服务器时,我不断收到此错误。 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

10678
2017-12-03 17:39


起源

与解决问题/问题没有直接关系,但据我所知,凤凰城的最佳做法是 以单数形式命名您的域对象 而不是复数(例如 defmodule AwesomeLunch.Location, LocationController等)。这样你就没有令人困惑的惯例,有时指的是单数,有时也指复数,就像在Rails世界中一样。 - Topher Hunt


答案:


Elixir中的模块需要以其全名或名称来引用 alias 它你可以改变所有 Locations 至 AwesomeLunch.Locations,或者如果你想使用较短的名字,你可以打电话 alias 在那个模块中:

defmodule AwesomeLunch.LocationsController do
  alias AwesomeLunch.Locations

  ...
end

15
2017-12-03 17:46





我有同样的错误,对我来说它配置控制器,这样:

defmodule AwesomeLunch.LocationsController do
  use AwesomeLunch.Web, :controller

  alias AwesomeLunch.Locations

  ...
end

0
2018-02-15 00:42