如何在Phoenix选择字段中显示模型的所有记录 [英] How to show all records of a model in Phoenix select field
问题描述
我有以下型号...
-
Page
-
Category
Page
Category
我在page_controller.ex
def new(conn, _params) do
changeset = Page.changeset(%Page{})
categories = Repo.all(Category)
render(conn, "new.html", changeset: changeset, categories: categories)
end
在page/new.html.eex中,我有以下用于选择字段的代码
I have following code for select field in page/new.html.eex
<div class="form-group">
<%= label f, :category_id, "Parent", class: "control-label" %>
<%= select f, :category_id, @categories ,class: "form-control" %>
</div>
它应该在选择字段中显示所有类别,因此我可以为页面选择一个类别,但是不幸的是我找不到问题.如果您有任何建议,请告诉我.
It should show all categories in select field so i can choose one category for the page but unfortunately i am unable to find the problem. if you have any suggestion please let me know.
推荐答案
select/4 函数需要第三个参数的元组列表.
The select/4 function expects a list of tuples for the 3rd argument.
从文档中
值应该是包含两个项目元组(例如映射和关键字列表)的Enumerable,或者是将元素用作生成的select的键和值的任何Enumerable.
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.
尝试将您的控制器更改为:
Try changing your controller to:
categories = Repo.all(Category) |> Enum.map(&{&1.name, &1.id})
这也可以在查询级别完成:
This can also be done at the query level:
query = from(c in Category, select: {c.name, c.id})
categories = Repo.all(query)
请参见凤凰城:订购查询集,以获取有关将查询定义为模型中的功能.
See Phoenix: Ordering a query set for an explanation of defining a query as a function in your model.
这篇关于如何在Phoenix选择字段中显示模型的所有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!