关联模型列表的 Elixir Phoenix 助手

Elixir Phoenix helper for associated model list

我有一个应用程序,其中列出了 parents 和 children。当我添加 child 时,我需要获取 parents 的列表以显示为下拉列表。 Phoenix 中有 Rails 中的 collection_select 之类的东西吗?我想显示用户名并使用 user_id 作为参数。

我还想将 parents 列表的范围限定为 site_id。

您可以使用 Phoenix.HTML.Form 中的 select/4 函数。

在您的控制器中,您可以通过查询获取父项:

query = from(p in Parent, select: {p.id, p.name})
parents = Repo.all(query)

我们需要此查询的原因是将值格式化为预期格式:

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.

然后您可以在模板中使用 select/4

<%= select f, :parent_id, @parents ,class: "form-control" %>

您还可以使用 Enum 转换记录。map/2 如果您已经有了父项:

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

控制器

all_parents = Repo.all from p in Parent, select: {p.name, p.id}

eex

<%= select f, :parent_id, @all_parents %>