问题
I have following models...
Page
Category
i have following code in new
action of 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
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.
回答1:
The select/4 function expects a list of tuples for the 3rd argument.
From the docs:
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.
来源:https://stackoverflow.com/questions/33805309/how-to-show-all-records-of-a-model-in-phoenix-select-field