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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With