How to show all records of a model in Phoenix select field

不羁岁月 提交于 2019-12-12 15:07:01

问题


I have following models...

  1. Page
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!