如何在 Phoenix select 字段中显示模型的所有记录

How to show all records of a model in Phoenix select field

我有以下型号...

  1. Page
  2. Category

我在 page_controller.ex

new 操作中有以下代码
def new(conn, _params) do
  changeset = Page.changeset(%Page{})
  categories = Repo.all(Category)
  render(conn, "new.html", changeset: changeset, categories: categories)
end

我在 page/new 中的 select 字段有以下代码。html.eex

<div class="form-group">
  <%= label f, :category_id, "Parent", class: "control-label" %>
  <%= select f, :category_id, @categories ,class: "form-control" %>
</div>

它应该在 select 字段中显示所有类别,这样我就可以为页面选择一个类别,但不幸的是我找不到问题所在。如果您有任何建议,请告诉我。

select/4 函数需要一个元组列表作为第三个参数。

来自文档:

Values are expected to be an Enumerable containing two-item tuples (like maps and keyword lists) or any Enumerable where the element will be used both as key and value for the generated select.

尝试将您的控制器更改为:

categories = Repo.all(Category) |> Enum.map(&{&1.name, &1.id})

这也可以在查询级别完成:

query = from(c in Category, select: {c.name, c.id})
categories = Repo.all(query)

有关在模型中将查询定义为函数的说明,请参阅