gpt4 book ai didi

用于关联模型列表的 Elixir Phoenix 助手

转载 作者:行者123 更新时间:2023-12-04 13:59:02 31 4
gpt4 key购买 nike

我有一个应用程序,我可以在其中列出 parent 和 child 。当我添加一个 child 时,我需要获得一个 parent 列表作为下拉列表显示。有没有类似 collection_select 的东西在 Phoenix 可用的 Rails 中?我想显示用户名并使用 user_id 作为参数。

我还想通过 site_id 来确定 parent 列表的范围。

最佳答案

您可以使用 select/4函数来自 Phoenix.HTML.Form .

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

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" %>

如果您已经有了 parent ,您还可以使用 Enum.map/2 转换记录:
parents = Repo.all(Parent) |> Enum.map(&{&1.id, &1.name})

关于用于关联模型列表的 Elixir Phoenix 助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34102960/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com