gpt4 book ai didi

elixir - 如何从 Phoenix 框架中的单独模型中创建带有选项和值的选择标签

转载 作者:行者123 更新时间:2023-12-02 05:45:31 27 4
gpt4 key购买 nike

我有一个相对简单的表单,带有选择标记(下拉表单字段)。

选择标记的选项/值是动态的,应该在我的类别模型更新时更新。

这是我现在得到的:

表单通过 web/templates/posts/new.html.eex 模板呈现,如下所示:

<%= render "form.html", changeset: @changeset,
action: project_path(@conn, :create) %>

这是web/templates/posts/form.html.eex中的相关表单字段

  <div class="form-group">
<%= select f, :category, MyApp.Category, class: "form-control" %>
<%= error_tag f, :category %>
</div>

但我收到以下错误:

protocol Enumerable not implemented for MyApp.Category

如何使用我的类别存储库作为表单中的选择标签选项?

编辑:我已经按照 Gazler 的建议在 PostController 的新操作中获取了类别(感谢 Gaz)。

def new
categories = Repo.all(MyApp.Category)
changeset =
user
|> build_assoc(:projects)
|> Project.changeset()
render(conn, "new.html", changeset: changeset)
end

并更新了我的模板:

  <div class="form-group">
<%= select f, :category, @categories, class: "form-control" %>
<%= error_tag f, :category %>
</div>

现在我收到以下错误:

assign @categories not available in eex template.

编辑:看起来也许我应该使用 multiple_select/4 作为 Aaron did here因为我想要显示类别标题的选项和作为类别 ID 的值。

答案:

最终使用了 Gazler 发布的链接中的这一行(在我的 post_controller 的新操作中):

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

最佳答案

您需要获取您的选项(在 Controller 中):

def new(conn, params) do
query = from(c in Category, select: {c.id, c.name})
categories = Repo.all(query)
changeset =
user
|> build_assoc(:projects)
|> Project.changeset()
render(conn, "new.html", changeset: changeset, categories: categories)
end

那么你应该在选择中使用它。不是从 :category 更改为 :category_id

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

您可能需要转换选项。请参阅How to show all records of a model in Phoenix select field了解如何执行此操作。

关于elixir - 如何从 Phoenix 框架中的单独模型中创建带有选项和值的选择标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36698192/

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